/**
   * @param url
   * @param request
   * @param resContentHeaders
   * @param timeout
   * @return
   * @throws java.lang.Exception
   * @deprecated As of proxy release 1.0.10, replaced by {@link #sendRequestoverHTTPS( boolean
   *     isBusReq, URL url, String request, Map resContentHeaders, int timeout)}
   */
  public static String sendRequestOverHTTPS(
      URL url, String request, Map resContentHeaders, int timeout) throws Exception {

    // Set up buffers and streams
    StringBuffer buffy = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      // this makes the assumption that all https requests are going to the bus using UTF-8 encoding
      String encodedString =
          URLEncoder.encode(request, FastHttpClientConstants.HTTP_REQUEST_ENCODING);
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      out.write(FastHttpClientConstants.HTTP_REQUEST_POST_KEY.getBytes());
      out.write(encodedString.getBytes());
      out.flush();

      // Response
      // this mangles 2 or more byte characters
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      buffy = new StringBuffer(INPUT_BUFFER_LEN);
      int ch = 0;
      while ((ch = in.read()) > -1) {
        buffy.append((char) ch);
      }

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return buffy == null ? null : buffy.toString();
  }
示例#2
0
  public static void downloadPDF(String url, String downloadPath)
      throws IOException, JSONException {

    URL u = new URL(url);
    HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
    uc.setRequestMethod("GET");
    String authentication =
        "<DocuSignCredentials><Username>"
            + Data.USERNAME
            + "</Username><Password>"
            + Data.PASSWORD
            + "</Password><IntegratorKey>"
            + Data.INTEGRATOR_KEY
            + "</IntegratorKey></DocuSignCredentials>";
    uc.setRequestProperty("X-DocuSign-Authentication", authentication);
    uc.setRequestProperty("Content-type", "application/pdf");
    uc.setRequestProperty("Accept", "application/pdf");
    File file = new File(downloadPath);
    FileOutputStream fileOutput = new FileOutputStream(file);
    InputStream is = uc.getInputStream();
    try {
      byte[] buffer = new byte[1024];
      int bufferLength = 0; // used to store a temporary size of the
      // buffer
      while ((bufferLength = is.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);
      }
      fileOutput.close();
    } finally {
      is.close();
    }
  }
示例#3
0
  // Get data given REST URL
  public String getData(String uri) {

    BufferedReader reader = null;
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setRequestMethod("GET");
      StringBuilder sb = new StringBuilder();
      reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
          return null;
        }
      }
    }
  }
示例#4
0
  // Add a new user
  public String addUser(String uri, String j) {
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setRequestMethod("POST");

      OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
      out.write(j);
      out.flush();
      out.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      String inputLine;
      StringBuffer response = new StringBuffer();

      while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
      }

      Log.d("AddUserReponse", response.toString());
      in.close();

      return "success";
    } catch (Exception e) {
      e.printStackTrace();
      return "fail";
    }
  }
示例#5
0
 /**
  * Connects to the web site and parses the information into enties.
  *
  * @return A List of Entries.
  */
 public List<Entry> reload(String zip) {
   entries = null;
   parser = new XmlParser();
   try {
     url = new URL("https://www.phillykeyspots.org/keyspot-mobile-map.xml/" + zip + "_2");
     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
     conn.setReadTimeout(10000 /*milliseconds*/);
     conn.setConnectTimeout(15000 /*milliseconds*/);
     conn.setRequestMethod("GET");
     conn.setDoInput(true);
     conn.connect();
     stream = conn.getInputStream();
     entries = parser.parse(stream);
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (stream != null) {
       try {
         stream.close();
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
   return entries;
 }
示例#6
0
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    // Send HTTP POST request to server
    URL url = new URL("https://localhost:" + serverPort);

    HttpsURLConnection.setDefaultHostnameVerifier(new NameVerifier());
    HttpsURLConnection http = (HttpsURLConnection) url.openConnection();
    http.setDoOutput(true);

    http.setRequestMethod("POST");
    PrintStream ps = new PrintStream(http.getOutputStream());
    try {
      ps.println(postMsg);
      ps.flush();
      if (http.getResponseCode() != 200) {
        throw new RuntimeException("test Failed");
      }
    } finally {
      ps.close();
      http.disconnect();
      closeReady = true;
    }
  }
示例#7
0
  /**
   * Parses the url connection.
   *
   * @param url the url
   * @param apiKey the api key
   * @param requestMethod the request method
   * @param data the data
   * @return the string
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws JSONException the jSON exception
   */
  public static String parseUrlConnection(String url, String requestMethod, String data)
      throws IOException, JSONException {

    URL u = new URL(url);
    HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
    uc.setRequestMethod(requestMethod);
    String authentication =
        "<DocuSignCredentials><Username>"
            + Data.USERNAME
            + "</Username><Password>"
            + Data.PASSWORD
            + "</Password><IntegratorKey>"
            + Data.INTEGRATOR_KEY
            + "</IntegratorKey></DocuSignCredentials>";
    uc.setRequestProperty("X-DocuSign-Authentication", authentication);
    uc.setRequestProperty("Content-type", "application/json");
    uc.setRequestProperty("Accept", "application/json");
    if (data != null) {
      uc.setDoOutput(true);
      OutputStreamWriter postData = new java.io.OutputStreamWriter(uc.getOutputStream());
      postData.write(data);
      postData.flush();
      postData.close();
    }
    InputStream is = uc.getInputStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      return jsonText;
    } finally {
      is.close();
    }
  }
    public void taskData() {
      if ("https".equals(url.getProtocol())) {
        HttpsURLConnection httpsUrlConnection;
        try {

          URLrequestection = url.openConnection();
          httpsUrlConnection = (HttpsURLConnection) URLrequestection;
          httpsUrlConnection.setRequestMethod("GET");
        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }

      } else {
        URLConnection URLrequestection;
        HttpURLConnection httpUrlConnection;
        try {
          URLrequestection = url.openConnection();
          httpUrlConnection = (HttpURLConnection) URLrequestection;
          httpUrlConnection.setRequestMethod("GET");

        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }
      }
    }
示例#9
0
 /**
  * 方法名:httpRequest</br> 详述:发送http请求</br> 开发人员:souvc </br> 创建时间:2016-1-5 </br>
  *
  * @param requestUrl
  * @param requestMethod
  * @param outputStr
  * @return 说明返回值含义
  * @throws 说明发生此异常的条件
  */
 private static JsonNode httpRequest(String requestUrl, String requestMethod, String outputStr) {
   StringBuffer buffer = new StringBuffer();
   JsonNode josnNode = null;
   JSONObject jsonObject = null;
   try {
     URL url = new URL(requestUrl);
     HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
     httpUrlConn.setRequestMethod("GET");
     httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     httpUrlConn.setDoOutput(true);
     httpUrlConn.setDoInput(true);
     httpUrlConn.setUseCaches(false);
     System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); // 连接超时30秒
     System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
     httpUrlConn.connect();
     InputStream inputStream = httpUrlConn.getInputStream();
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
     BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
     String str = null;
     while ((str = bufferedReader.readLine()) != null) {
       buffer.append(str);
     }
     josnNode = new ObjectMapper().readTree(buffer.toString());
     bufferedReader.close();
     inputStreamReader.close();
     inputStream.close();
     inputStream = null;
     httpUrlConn.disconnect();
   } catch (ConnectException ce) {
     ce.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return josnNode;
 }
  /**
   * Synchronous call for logging in
   *
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    HttpsURLConnection connection = createSecureConnection(url);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    OutputStream os = new BufferedOutputStream(connection.getOutputStream());
    os.write(encodePostBody(httpBody).getBytes());
    os.flush();
    try {
      LoggingUtils.d(LOG_TAG, connection.toString());
      response = readFromStream(connection.getInputStream());
    } catch (MalformedURLException e) {
      LoggingUtils.e(
          LOG_TAG,
          "Error reading stream \""
              + connection.getInputStream()
              + "\". "
              + e.getLocalizedMessage(),
          null);
    } catch (IOException e) {
      response = readFromStream(connection.getErrorStream());
    } finally {
      connection.disconnect();
    }

    return response;
  }
 public static boolean isAddressReachable(String url) {
   URLConnection urlConnection = null;
   try {
     urlConnection = new URL(url).openConnection();
     if (url.contains("https")) {
       HttpsURLConnection urlConnect = (HttpsURLConnection) urlConnection;
       urlConnect.setConnectTimeout(5000);
       urlConnect.setReadTimeout(30000);
       urlConnect.setInstanceFollowRedirects(false);
       urlConnect.setRequestMethod("HEAD");
       int responseCode = urlConnect.getResponseCode();
       urlConnect.disconnect();
       urlConnect = null;
       return (responseCode == HttpURLConnection.HTTP_OK);
     } else {
       HttpURLConnection urlConnect = (HttpURLConnection) urlConnection;
       urlConnect.setConnectTimeout(5000);
       urlConnect.setReadTimeout(30000);
       urlConnect.setInstanceFollowRedirects(false);
       urlConnect.setRequestMethod("HEAD");
       int responseCode = urlConnect.getResponseCode();
       urlConnect.disconnect();
       urlConnect = null;
       return (responseCode == HttpURLConnection.HTTP_OK);
     }
   } catch (Exception e) {
   } finally {
     if (urlConnection != null) {
       urlConnection = null;
     }
   }
   return false;
 }
  @Override
  protected HttpURLConnection openConnection(String path, String query) throws IOException {
    query = addDelegationTokenParam(query);
    final URL url = new URL("https", nnAddr.getHostName(), nnAddr.getPort(), path + '?' + query);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    // bypass hostname verification
    try {
      conn.setHostnameVerifier(new DummyHostnameVerifier());
      conn.setRequestMethod("GET");
      conn.connect();
    } catch (IOException ioe) {
      throwIOExceptionFromConnection(conn, ioe);
    }

    // check cert expiration date
    final int warnDays = ExpWarnDays;
    if (warnDays > 0) { // make sure only check once
      ExpWarnDays = 0;
      long expTimeThreshold = warnDays * MM_SECONDS_PER_DAY + System.currentTimeMillis();
      X509Certificate[] clientCerts = (X509Certificate[]) conn.getLocalCertificates();
      if (clientCerts != null) {
        for (X509Certificate cert : clientCerts) {
          long expTime = cert.getNotAfter().getTime();
          if (expTime < expTimeThreshold) {
            StringBuilder sb = new StringBuilder();
            sb.append("\n Client certificate " + cert.getSubjectX500Principal().getName());
            int dayOffSet = (int) ((expTime - System.currentTimeMillis()) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            LOG.warn(sb.toString());
          }
        }
      }
    }
    return (HttpURLConnection) conn;
  }
  /**
   * Executa a operação da API informando um Builder para a requisição e resposta.
   *
   * @param requestBuilder é uma instância de {@link AkatusRequestBuilder} responsável pela criação
   *     do corpo da requisição.
   * @param responseBuilder é uma instância de {@link AkatusResponseBuilder} responsável pela
   *     criação do objeto que representa a resposta.
   * @return Uma instância de {@link AkatusResponse} com a resposta da operação.
   */
  public AkatusResponse execute(
      AkatusRequestBuilder requestBuilder, AkatusResponseBuilder responseBuilder) {

    AkatusResponse response = new AkatusResponse();

    try {
      final URL url = new URL(akatus.getHost() + getPath());
      final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", requestBuilder.getContentType());

      final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

      writer.write(requestBuilder.build(this));
      writer.flush();

      try {
        response = responseBuilder.build(readResponse(connection.getInputStream()));
      } catch (final IOException e) {
        response = responseBuilder.build(readResponse(connection.getErrorStream()));
      }
    } catch (final Exception e) {
      Logger.getLogger(AkatusOperation.class.getName())
          .throwing(this.getClass().getName(), "execute", e);
    }

    return response;
  }
示例#14
0
  public String doGet(String urlstr) throws IOException {
    URL url = new URL(urlstr);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    fetchReqMap(connection); // 设置请求属性
    connection.setReadTimeout(timeout);
    connection.setDoOutput(false); // true for POST, false for GET
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);

    String aLine = null;
    String ret = "";
    InputStream is = connection.getInputStream();
    BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode()));

    while ((aLine = aReader.readLine()) != null) {
      ret += aLine + "\r\n";
      ;
    }

    aReader.close();
    connection.disconnect();

    return ret;
  }
 @Override
 public String receiveData(String urlPath, String streamData) {
   StringBuilder responseStringBuilder = new StringBuilder();
   URL url = null;
   URLConnection urlConnection = null;
   Scanner scanner = null;
   try {
     url = new URL(urlPath);
     urlConnection = url.openConnection();
     HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection;
     httpsUrlConnection.setDoOutput(true);
     httpsUrlConnection.setDoInput(true);
     httpsUrlConnection.setUseCaches(false);
     httpsUrlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
     httpsUrlConnection.setRequestMethod("POST");
     httpsUrlConnection.connect();
     if (streamData != null) {
       OutputStream outputStream = httpsUrlConnection.getOutputStream();
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
       outputStreamWriter.write(streamData);
       outputStreamWriter.flush();
       outputStreamWriter.close();
     }
     scanner = new Scanner(urlConnection.getInputStream(), "UTF-8");
     while (scanner.hasNext()) {
       String tempString = scanner.nextLine().trim();
       responseStringBuilder.append(tempString);
     }
     scanner.close();
   } catch (Exception e) {
     return null;
   }
   return responseStringBuilder.toString();
 }
示例#16
0
    @Override
    public Void doInBackground(String... params) {
      HttpsURLConnection connection = null;

      try {
        URL url = new URL(SEARCH_URL + params[0]);
        Log.d("****URL:", url.toString());
        connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "api.twitter.com");
        connection.setRequestProperty("User-Agent", "JustDoIt");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
        connection.setUseCaches(false);

        JSONObject obj = new JSONObject(ReadResponse.readResponse(connection));

        buildTweets(obj);

        Log.d("***GetTweets:", obj.toString());

      } catch (MalformedURLException e) {
        Log.e("***GetTweets", "Invalid endpoint URL specified.", e);

      } catch (IOException e) {
        Log.e("***GetTweets", "IOException: ", e);
      } catch (JSONException e) {
        e.printStackTrace();
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
        lock.release();
      }
      return null;
    }
  @Test
  public void testSendMessage() throws Exception {
    String url = getAppBaseURL() + "send_message";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String body = "message=" + URLEncoder.encode(MESSAGE, "UTF-8");

    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestMethod("POST");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();

    // It ensures that the app successfully received the message.
    assertEquals(204, responseCode);

    // Try fetching the /fetch_messages endpoint and see if the
    // response contains the message.
    boolean found = false;
    for (int i = 0; i < MAX_RETRY; i++) {
      Thread.sleep(SLEEP_TIME);
      String resp = fetchMessages();
      if (resp.contains(MESSAGE)) {
        found = true;
        break;
      }
    }
    assertTrue(found);
  }
 /**
  * HttpUrlConnection支持所有Https免验证,不建议使用
  *
  * @throws KeyManagementException
  * @throws NoSuchAlgorithmException
  * @throws IOException
  */
 public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {
   URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version");
   SSLContext context = SSLContext.getInstance("TLS");
   context.init(null, new TrustManager[] {new TrustAllManager()}, null);
   HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
   HttpsURLConnection.setDefaultHostnameVerifier(
       new HostnameVerifier() {
         @Override
         public boolean verify(String arg0, SSLSession arg1) {
           return true;
         }
       });
   HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
   connection.setDoInput(true);
   connection.setDoOutput(false);
   connection.setRequestMethod("GET");
   connection.connect();
   InputStream in = connection.getInputStream();
   BufferedReader reader = new BufferedReader(new InputStreamReader(in));
   String line = "";
   StringBuffer result = new StringBuffer();
   while ((line = reader.readLine()) != null) {
     result.append(line);
   }
   String reString = result.toString();
   Log.i("TTTT", reString);
 }
示例#19
0
  private static HttpsURLConnection getFeed(String downloadUrl) {
    HttpsURLConnection urlConnection = null;
    try {
      URL url = new URL(downloadUrl);
      urlConnection = (HttpsURLConnection) url.openConnection();
      urlConnection.setUseCaches(false);
      urlConnection.setDefaultUseCaches(false);
      urlConnection.setRequestMethod("GET");
      urlConnection.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");
      urlConnection.setRequestProperty("Upgrade-Insecure-Requests", "1");
      urlConnection.setRequestProperty("Connection", "keep-alive");
      urlConnection.setRequestProperty("Cache-Control", "max-age=0");
      urlConnection.setRequestProperty(
          "Accept-Language", "en-US,en;q=0.8,fr-FR;q=0.6,fr;q=0.4,en-AU;q=0.2");
      urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
      urlConnection.setRequestProperty(
          "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
      long currentTime = System.currentTimeMillis();
      long expires = urlConnection.getHeaderFieldDate("Expires", currentTime);
      long lastModified = urlConnection.getHeaderFieldDate("Last-Modified", currentTime);

      urlConnection.setInstanceFollowRedirects(true);
      //            InputStream inputStream = urlConnection.getInputStream();
      return urlConnection;
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //            urlConnection.disconnect();
    }
    return null;
  }
  private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) {
    SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con = null;
    try {
      con = (HttpsURLConnection) url.openConnection();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }
    con.setSSLSocketFactory(sslFactory);
    try {
      con.setRequestMethod(REQUEST_METHOD_GET);
    } catch (ProtocolException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION);

    InputStream responseStream = null;
    try {
      responseStream = (InputStream) con.getContent();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    return responseStream;
  }
示例#21
0
  public String doPost(String urlstr, byte data[]) throws IOException {
    URL url = new URL(urlstr);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    fetchReqMap(connection);
    //
    // connection.setRequestProperty("SOAPAction","https://hms.wellcare.cn:8443/services/EnergyData");

    connection.setReadTimeout(timeout);
    connection.setDoOutput(true); // true for POST, false for GET
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);

    // 写入post数据
    OutputStream out = connection.getOutputStream();
    out.write(data);

    // 读出反馈结果
    String aLine = null;
    String ret = "";
    InputStream is = connection.getInputStream();
    BufferedReader aReader = new BufferedReader(new InputStreamReader(is, this.getRespEncode()));

    while ((aLine = aReader.readLine()) != null) {
      ret += aLine + "\r\n";
    }

    aReader.close();
    connection.disconnect();

    return ret;
  }
  protected Void doInBackground(Integer... params) {
    Integer genreId = params[0];
    final String BASE_URL = "https://api.themoviedb.org/3/";
    final String MOVIES_OF_GENRE_LIST_METHOD = "genre/" + genreId + "/movies";
    final String API_KEY_PARAM = "api_key";
    final String API_KEY_VALUE = "21ac243915da272c3c6b92a9958a3650";
    //        final String REQUEST_TOKEN_PARAM = "request_token";
    //        final String SESSION_ID_PARAM = "session_id";
    //        final String USER_NAME_PARAM = "username";
    //        final String PASSWORD_PARAM = "password";

    BufferedReader reader = null;
    HttpsURLConnection urlConnection = null;
    String moviesListJson = null;
    Uri builtUri =
        Uri.parse(BASE_URL + MOVIES_OF_GENRE_LIST_METHOD)
            .buildUpon()
            .appendQueryParameter(API_KEY_PARAM, API_KEY_VALUE)
            .build();
    try {
      URL url = new URL(builtUri.toString());
      urlConnection = (HttpsURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setRequestProperty("Accept", "application/json");
      urlConnection.connect();

      InputStream inputStream = urlConnection.getInputStream();
      StringBuffer buffer = new StringBuffer();
      if (inputStream == null) {
        Log.e(LOG_TAG, "INPUT STREAM from http request returned nothing");
        return null;
      }
      reader = new BufferedReader(new InputStreamReader(inputStream));
      String ln;
      while ((ln = reader.readLine()) != null) {
        buffer.append(ln + "\n");
      }
      if (buffer.length() == 0) {
        Log.e(LOG_TAG, "empty buffer from http request, no data found");
        return null;
      }
      moviesListJson = buffer.toString();
    } catch (IOException e) {
      Log.e(LOG_TAG, "Error ", e);
      return null;
    }
    try {
      JSONObject moviesListObject = new JSONObject(moviesListJson);
      int page = moviesListObject.getInt("page");
      int pages = moviesListObject.getInt("total_pages");
      JSONArray results = moviesListObject.getJSONArray("results");
      mMovies = Movie.fromJson(results);
    } catch (JSONException e) {
      Log.e(LOG_TAG, "Error: ", e);
      return null;
    }
    return null;
  }
示例#23
0
  public ServiceUser getServiceUser(String accessToken, String refreshToken) {
    ServiceUser result = null;

    try {
      String url =
          "https://api.linkedin.com/v1/people/~:(first-name,last-name,formatted-name,id,main-address,email-address,im-accounts,twitter-accounts,site-standard-profile-request,location,picture-url)";
      url += "?format=json&oauth2_access_token=" + accessToken;

      URL obj = new URL(url);
      HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      con.setRequestMethod("GET");

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

      JsonParser parser = new JsonParser();
      JsonElement jsonUserInfo = parser.parse(in);
      if (jsonUserInfo != null && (jsonUserInfo instanceof JsonObject)) {
        result = new ServiceUser();
        result.setAreRoleNamesAccurate(useRoleNames);

        // This is set here in the case we had to refresh this access token.
        result.setAccessToken(accessToken);

        result.setId(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "id"));

        result.setFirstName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "firstName"));
        result.setLastName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "lastName"));
        result.setName(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "formattedName"));

        result.setAvatarUrl(getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "pictureUrl"));

        List<ServiceIdentifier> identifiers = new ArrayList<ServiceIdentifier>();
        identifiers.add(new ServiceIdentifier(ServiceIdentifier.LINKED_ID, result.getId()));
        result.setIdentifiers(identifiers);

        List<String> emails = new ArrayList<String>();
        String email = getJsonObjectStringValue(jsonUserInfo.getAsJsonObject(), "emailAddress");
        emails.add(email);
        identifiers.add(new ServiceIdentifier(ServiceIdentifier.EMAIL, email));
        result.setEmails(emails);
        result.setLink(
            getJsonObjectStringValue(
                jsonUserInfo.getAsJsonObject().getAsJsonObject("siteStandardProfileRequest"),
                "url"));
        result.setLocale(
            getJsonObjectStringValue(
                jsonUserInfo.getAsJsonObject().getAsJsonObject("location"), "name"));
      } else {
        log.debug("Unable to get Google Profile Information. User information was not populated");
      }
    } catch (Exception e) {
      log.error("Error getting ServiceUser", e);
    }

    return result;
  }
  public static String sendRequestOverHTTPS(
      boolean isBusReq, URL url, String request, Map resContentHeaders, int timeout)
      throws Exception {

    // Set up buffers and streams
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    String fullResponse = null;

    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      sendRequestString(isBusReq, out, request);

      // recv response
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      String contentType = urlc.getHeaderField("Content-Type");
      fullResponse = receiveResponseString(in, contentType);

      out.close();
      in.close();

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return fullResponse;
  }
示例#25
0
  /**
   * 发起https请求并获取结果
   *
   * @param requestUrl 请求地址
   * @param requestMethod 请求方式(GET、POST)
   * @param outputStr 提交的数据
   * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
   */
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    //
    log.info("https请求url是" + requestUrl);
    try {
      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());
      // 从上述SSLContext对象中得到SSLSocketFactory对象
      SSLSocketFactory ssf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);
      HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
      httpUrlConn.setSSLSocketFactory(ssf);

      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);
      // 设置请求方式(GET/POST)
      httpUrlConn.setRequestMethod(requestMethod);

      // if ("GET".equalsIgnoreCase(requestMethod))
      // httpUrlConn.connect();

      // 当有数据需要提交时
      if (null != outputStr) {
        OutputStream outputStream = httpUrlConn.getOutputStream();
        // 注意编码格式,防止中文乱码
        outputStream.write(outputStr.getBytes("UTF-8"));
        outputStream.close();
      }

      // 将返回的输入流转换成字符串
      InputStream inputStream = httpUrlConn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str = null;
      StringBuffer buffer = new StringBuffer();
      while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
      }
      bufferedReader.close();
      inputStreamReader.close();
      // 释放资源
      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
      log.error("连接超时", ce);
    } catch (Exception e) {
      log.error("请求异常", e);
    }
    return jsonObject;
  }
示例#26
0
  public JSONObject httpsRequest(String requestUrl, String httpMethod, String defaultStr) {
    JSONObject res = new JSONObject();
    try {
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new SecureRandom());
      SSLSocketFactory sf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setSSLSocketFactory(sf);
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.setRequestMethod(httpMethod);

      if (defaultStr != null) {
        OutputStream os = conn.getOutputStream();
        os.write(defaultStr.getBytes("UTF-8"));
        os.close();
      }

      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "UTF-8");
      BufferedReader br = new BufferedReader(isr);

      String str = null;
      StringBuffer sb = new StringBuffer();
      while ((str = br.readLine()) != null) {
        sb.append(str);
      }
      br.close();
      isr.close();
      is.close();
      is = null;
      conn.disconnect();

      res = JSONObject.fromObject(sb.toString());

    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return res;
  }
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

      e.printStackTrace();
    }
    try {
      sc.init(
          null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {

      e.printStackTrace();
    }
    URL console = null;
    try {
      console = new URL(url);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    HttpsURLConnection conn;
    try {
      conn = (HttpsURLConnection) console.openConnection();
      conn.setRequestMethod("POST");
      conn.setSSLSocketFactory(sc.getSocketFactory());
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setRequestProperty("Accept", "application/json");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json"
      String inpputs = contentdata;
      OutputStream os = conn.getOutputStream();
      os.write(inpputs.getBytes());
      os.close();
      conn.connect();
      InputStream is = conn.getInputStream();
      // // DataInputStream indata = new DataInputStream(is);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String ret = "";
      while (ret != null) {
        ret = reader.readLine();
        if (ret != null && !ret.trim().equals("")) {
          str_return = str_return + ret;
        }
      }
      is.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return str_return;
  }
  public void open() throws IOException {
    log.debug("opening live stream connection to " + this.endpointUrl);
    URL url = new URL(this.endpointUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(10000);
    connection.setRequestProperty("Authorization", "Bearer " + this.accessToken);
    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setRequestMethod("GET");

    log.debug("HTTP response code " + connection.getResponseCode());

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      throw new IOException(
          connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
    }

    InputStream inputStream = new GZIPInputStream(connection.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    long start_time = System.currentTimeMillis() / 1000; // now should be in seconds
    int records_received = 0;
    int bytes_received = 0;

    String line;
    while ((line = reader.readLine()) != null) {
      if (line.length() > 0) {
        records_received += 1;
        bytes_received += line.length();
      }
      long now = System.currentTimeMillis() / 1000; // now should be in seconds
      long elapsed_time = now - start_time;
      if (elapsed_time > STREAM_RATE_SAMPLE_PERIOD_SECONDS) {
        float stream_rate = (float) records_received / (float) elapsed_time;
        float transfer_rate = (float) bytes_received / (float) elapsed_time / (float) 1024.0;
        System.out.println(
            "stream rate calculated: "
                + stream_rate
                + " records/second, read "
                + records_received
                + " records in "
                + elapsed_time
                + " seconds");
        System.out.println(
            "transfer rate calculated: "
                + transfer_rate
                + " kb/second, read "
                + bytes_received
                + " bytes in "
                + elapsed_time
                + " seconds");
        System.out.println("-------------------------------------");
      }
    }
  }
示例#29
0
  private void testIt() {

    String https_url = requestURL;
    URL url;

    SSLSocketFactory socketFactory = null;

    try {

      try {
        socketFactory = createSSLContext().getSocketFactory();
      } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      url = new URL(https_url);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setDoInput(true); // Allow Inputs
      conn.setDoOutput(true); // Allow Outputs
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setSSLSocketFactory(socketFactory);

      DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

      conn.addRequestProperty("app_id", app_id);
      conn.addRequestProperty("app_key", app_key);

      // dump all cert info
      // print_https_cert(con);

      // dump all the content
      print_content(conn);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#30
0
  public static String httpsRequestByWx(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());
      // 从上述SSLContext对象中得到SSLSocketFactory对象
      SSLSocketFactory ssf = sslContext.getSocketFactory();

      URL url = new URL(requestUrl);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setSSLSocketFactory(ssf);

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setUseCaches(false);
      // 设置请求方式(GET/POST)
      conn.setRequestMethod(requestMethod);

      // 当outputStr不为null时向输出流写数据
      if (null != outputStr) {
        OutputStream outputStream = conn.getOutputStream();
        // 注意编码格式
        outputStream.write(outputStr.getBytes("UTF-8"));
        outputStream.close();
      }

      // 从输入流读取返回内容
      InputStream inputStream = conn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String str = null;

      while ((str = bufferedReader.readLine()) != null) {
        buffer.append(str);
      }

      // 释放资源
      bufferedReader.close();
      inputStreamReader.close();
      inputStream.close();
      inputStream = null;
      conn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
      logger.error("连接超时:{}", ce);
    } catch (Exception e) {
      logger.error("https请求异常:{}", e);
    }
    return buffer.toString();
  }