Ejemplo n.º 1
0
 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;
 }
Ejemplo n.º 2
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;
    }
Ejemplo n.º 3
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;
    }
  }
Ejemplo n.º 4
0
 // Get the size of a file from URL response header.
 public static Long getRemoteSize(String url) {
   Long remoteSize = (long) 0;
   HttpURLConnection httpConn = null;
   HttpsURLConnection httpsConn = null;
   try {
     URI uri = new URI(url);
     if (uri.getScheme().equalsIgnoreCase("http")) {
       httpConn = (HttpURLConnection) uri.toURL().openConnection();
       if (httpConn != null) {
         String contentLength = httpConn.getHeaderField("content-length");
         if (contentLength != null) {
           remoteSize = Long.parseLong(contentLength);
         }
         httpConn.disconnect();
       }
     } else if (uri.getScheme().equalsIgnoreCase("https")) {
       httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
       if (httpsConn != null) {
         String contentLength = httpsConn.getHeaderField("content-length");
         if (contentLength != null) {
           remoteSize = Long.parseLong(contentLength);
         }
         httpsConn.disconnect();
       }
     }
   } catch (URISyntaxException e) {
     throw new IllegalArgumentException("Invalid URL " + url);
   } catch (IOException e) {
     throw new IllegalArgumentException("Unable to establish connection with URL " + url);
   }
   return remoteSize;
 }
Ejemplo n.º 5
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;
  }
Ejemplo n.º 6
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;
 }
Ejemplo n.º 7
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;
  }
  /**
   * 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 String requestBearerToken() throws IOException {
    HttpsURLConnection connection = null;
    String encodedCredentials =
        encodeKeys(BUNDLE.getString("twt.client_id"), BUNDLE.getString("twt.secret"));
    String endPointUrl = "https://api.twitter.com/oauth2/token";
    try {
      HttpServletResponse response =
          (HttpServletResponse)
              FacesContext.getCurrentInstance().getExternalContext().getResponse();
      response.setHeader("Host", "api.twitter.com");
      response.setHeader("User-Agent", "Iclub");
      response.setHeader("Authorization", "Basic " + encodedCredentials);
      response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
      response.setHeader("Content-Length", "29");
      ServletOutputStream fdsaf = response.getOutputStream();
      fdsaf.write("grant_type=client_credentials".getBytes());
      fdsaf.close();
      response.sendRedirect(endPointUrl);

      return new String();
    } catch (MalformedURLException e) {
      throw new IOException("Invalid endpoint URL specified.", e);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
Ejemplo n.º 10
0
  /**
   * Tests whether this client can make an HTTP connection with TLS 1.2.
   *
   * @return true if connection is successful. false otherwise.
   */
  public static boolean testTls12Connection() {
    String protocol = "N/A";
    try {
      SSLContext sslContext = SSLContext.getInstance(getLatestProtocol().toString());
      protocol = sslContext.getProtocol();
      sslContext.init(null, null, null);
      HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

      URL url = new URL("https://" + ENDPOINT);
      HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();

      httpsConnection.connect();
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(httpsConnection.getInputStream()));
      StringBuilder body = new StringBuilder();
      while (reader.ready()) {
        body.append(reader.readLine());
      }
      httpsConnection.disconnect();
      if (body.toString().equals("PayPal_Connection_OK")) {
        return true;
      }

    } catch (NoSuchAlgorithmException e) {
    } catch (UnknownHostException e) {
    } catch (IOException e) {
    } catch (KeyManagementException e) {
    }
    return false;
  }
Ejemplo n.º 11
0
  public static ArrayList<Deal> getDeals(
      String url, final RequestQueue requestQueue, int startPage, int endPage) {
    RequestFuture<String> requestFuture = RequestFuture.newFuture();
    ArrayList<Deal> deals = new ArrayList<>((endPage - startPage) * 10);

    String pageParam = null;
    for (int i = startPage; i < endPage; i++) {
      String xml = null;
      pageParam = String.format(L.PAGE_PARAM, i);

      StringRequest stringRequest =
          new StringRequest(Request.Method.GET, url + pageParam, requestFuture, requestFuture);

      try {
        requestQueue.add(stringRequest);
        xml = requestFuture.get(30000, TimeUnit.MILLISECONDS);
        HttpsURLConnection connection = getFeed(url + pageParam);
        try {

          deals.addAll(DomXmlMapper.xmlToDeal(connection.getInputStream()));
        } catch (Exception e) {

        } finally {
          connection.disconnect();
          Thread.sleep(100);
        }
        //                deals.addAll(DomXmlMapper.xmlToDeal(xml));

      } catch (Exception e) {
        L.d(TAG, "Error while retreiving feed", e);
      }
    }
    return deals;
  }
  public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
      throws AccessTokenException {
    SSLContext ctx;
    String response = "";
    try {
      ctx = SSLContext.getInstance("TLS");

      ctx.init(
          new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
      SSLContext.setDefault(ctx);

      URL url = new URL(tokenURL);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(
          new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
              return true;
            }
          });
      // System.out.println(conn.getResponseCode());
      conn.disconnect();

      HttpClient httpClient = new HttpClient();

      PostMethod postMethod = new PostMethod(tokenURL);
      postMethod.addParameter(new NameValuePair("grant_type", grantType));
      postMethod.addParameter(new NameValuePair("username", username));
      postMethod.addParameter(new NameValuePair("password", password));
      postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

      postMethod.addRequestHeader("Authorization", "Basic " + appToken);
      postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      httpClient.executeMethod(postMethod);

      response = postMethod.getResponseBodyAsString();
      log.info(response);
      JSONObject jsonObject = new JSONObject(response);

      AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
      accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
      accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
      accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
      accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

      return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {

      log.error(e.getMessage());
      throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

      return null;
    }
  }
Ejemplo n.º 13
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;
  }
  /**
   * The main RESTful GET method; the other one ({@link #make_restful_get(String, String, int)})
   * calls this one with a pre-populated logging parameter.
   *
   * @param baseUrl A {@link String} URL to request from.
   * @param tag A {@link String} tag for logging/analytics purposes.
   * @param timeout An {@link Integer} value containing the number of milliseconds to wait before
   *     considering a server request to have timed out.
   * @param log A {@link Boolean} value that specifies whether debug logging should be enabled for
   *     this request or not.
   * @return A {@link ServerResponse} object containing the result of the RESTful request.
   */
  private ServerResponse make_restful_get(
      String baseUrl, String tag, int timeout, int retryNumber, boolean log) {
    String modifiedUrl = baseUrl;
    JSONObject getParameters = new JSONObject();
    HttpsURLConnection connection = null;
    if (timeout <= 0) {
      timeout = DEFAULT_TIMEOUT;
    }
    if (addCommonParams(getParameters, retryNumber)) {
      modifiedUrl += this.convertJSONtoString(getParameters);
    } else {
      return new ServerResponse(tag, NO_BRANCH_KEY_STATUS);
    }

    try {
      if (log) PrefHelper.Debug("BranchSDK", "getting " + modifiedUrl);
      URL urlObject = new URL(modifiedUrl);
      connection = (HttpsURLConnection) urlObject.openConnection();
      connection.setConnectTimeout(timeout);
      connection.setReadTimeout(timeout);

      if (connection.getResponseCode() >= 500 && retryNumber < prefHelper_.getRetryCount()) {
        try {
          Thread.sleep(prefHelper_.getRetryInterval());
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        retryNumber++;
        return make_restful_get(baseUrl, tag, timeout, retryNumber, log);
      } else {
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK
            && connection.getErrorStream() != null) {
          return processEntityForJSON(
              connection.getErrorStream(), connection.getResponseCode(), tag, log, null);
        } else {
          return processEntityForJSON(
              connection.getInputStream(), connection.getResponseCode(), tag, log, null);
        }
      }
    } catch (SocketException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (UnknownHostException ex) {
      if (log)
        PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage());
      return new ServerResponse(tag, NO_CONNECTIVITY_STATUS);
    } catch (IOException ex) {
      if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage());
      return new ServerResponse(tag, 500);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
Ejemplo n.º 15
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;
  }
Ejemplo n.º 16
0
    // HTTP GET item from the server
    // Return 0 on success
    private Item2 getItem() {
      URL url;
      HttpsURLConnection urlConnection = null;
      Item2 item = null;
      String itemUrl = GET_ITEM_URL + "/" + mItem.getId();

      try {
        url = new URL(itemUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();

        // Set authentication instance ID
        urlConnection.setRequestProperty(
            MyConstants.HTTP_HEADER_INSTANCE_ID,
            InstanceID.getInstance(getApplicationContext()).getId());
        // Set content type
        urlConnection.setRequestProperty("Content-Type", "application/json");

        // Set timeout
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);

        // Vernon debug
        Log.d(LOG_TAG, urlConnection.getRequestMethod() + " " + urlConnection.getURL().toString());

        // Send and get response
        // getResponseCode() will automatically trigger connect()
        int responseCode = urlConnection.getResponseCode();
        String responseMsg = urlConnection.getResponseMessage();
        Log.d(LOG_TAG, "Response " + responseCode + " " + responseMsg);
        if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
          Log.d(LOG_TAG, "Server says the item was closed");
          status = UpdateItemStatus.ITEM_CLOSED;
          return null;
        }
        if (responseCode != HttpURLConnection.HTTP_OK) {
          Log.d(LOG_TAG, "Get item " + mItem.getId() + " failed");
          status = UpdateItemStatus.SERVER_FAILURE;
          return null;
        }

        // Get items from body
        InputStreamReader in = new InputStreamReader(urlConnection.getInputStream());
        item = new Gson().fromJson(in, Item2.class);
      } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Get item failed because " + e.getMessage());
        status = UpdateItemStatus.ANDROID_FAILURE;
      } finally {
        if (urlConnection != null) {
          urlConnection.disconnect();
        }
      }
      return item;
    }
Ejemplo n.º 17
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();
  }
Ejemplo n.º 18
0
  protected static String getResponseForXPayToken(
      String endpoint, String xpaytoken, String payload, String method, String crId)
      throws IOException {

    logRequestBody(payload, endpoint, xpaytoken, crId);
    HttpsURLConnection conn = null;
    OutputStream os;
    BufferedReader br = null;
    InputStream is;
    String output;
    String op = "";

    URL url1 = new URL(endpoint);
    //	getCertificate();

    conn = (HttpsURLConnection) url1.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("x-request-id", "1234");
    conn.setRequestProperty("x-pay-token", xpaytoken);
    conn.setRequestProperty("X-CORRELATION-ID", crId);

    if (!StringUtils.isEmpty(payload)) {
      os = conn.getOutputStream();
      os.write(payload.getBytes());
      os.flush();
    }
    if (conn.getResponseCode() >= 400) {
      is = conn.getErrorStream();
    } else {
      is = conn.getInputStream();
    }
    if (is != null) {
      br = new BufferedReader(new InputStreamReader(is));
      while ((output = br.readLine()) != null) {
        op += output;
      }
    }

    // Log the response Headers
    Map<String, List<String>> map = conn.getHeaderFields();
    // for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    logger.info("Response Headers: " + map.toString());
    // }

    conn.disconnect();
    logResponseBody(op);

    return op;
  }
  @Override
  protected String doInBackground(String... params) {

    String apiKey = params[0];
    String authToken = params[1];

    if (authToken == null || apiKey == null) {
      return null;
    }

    try {
      URL url =
          new URL(
              "https://ivle.nus.edu.sg/api/Lapi.svc/UserName_Get?APIKey="
                  + apiKey
                  + "&Token="
                  + authToken
                  + "&output=json");
      connection = (HttpsURLConnection) url.openConnection();
      connection.setConnectTimeout(60000);
      connection.setReadTimeout(60000);

      responseCode = connection.getResponseCode();

      if (responseCode == 200) {
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
          sb.append(line);
          line = br.readLine();
        }
        br.close();
        responseContent = sb.toString();
      } else {
        return null;
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    } finally {
      connection.disconnect();
    }

    return responseContent;
  }
Ejemplo n.º 20
0
  public static Object ConnectToServer(
      URL url, String jsoninput, boolean hasinput, boolean hasoutput, String requestMethod) {
    try {
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setSSLSocketFactory(ssf);
      con.setDoInput(true);
      con.setRequestMethod(requestMethod);
      OutputStream os = null;
      StringBuffer sb = null;
      StringBuffer log = new StringBuffer();
      log.append(requestMethod).append(":");
      log.append("url=").append(url).append(".");

      if (hasinput) {
        log.append("jsoninput=").append(jsoninput).append(".");
        if (jsoninput == null) {
          log.append("parameter error.");
          logger.error(log.toString());
        }
        con.setDoOutput(true);
        os = con.getOutputStream();
        os.write(jsoninput.getBytes());
        os.close();
      }

      if (hasoutput) {
        InputStream is = con.getInputStream();
        InputStreamReader inputstreamReader = new InputStreamReader(is);
        BufferedReader bufferedreader = new BufferedReader(inputstreamReader);
        String str = null;
        sb = new StringBuffer();
        while ((str = bufferedreader.readLine()) != null) {
          sb.append(str);
        }
        bufferedreader.close();
        inputstreamReader.close();
        is.close();
      }

      con.disconnect();
      return sb.toString();

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 21
0
  /**
   * 模拟http请求
   *
   * @param requestUrl URL
   * @return
   */
  private static JSONObject httpRequest(String requestUrl) {
    // TODO Auto-generated method stub
    JSONObject jsonObject = null;
    String requestMethod = "GET";
    StringBuffer buffer = new StringBuffer();
    try {

      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());

      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);

      httpUrlConn.setRequestMethod(requestMethod);

      if ("GET".equalsIgnoreCase(requestMethod)) 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);
      }
      bufferedReader.close();
      inputStreamReader.close();

      inputStream.close();
      inputStream = null;
      httpUrlConn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
      log.error("http请求数据失败�?" + ce.getMessage());
    } catch (Exception e) {
      log.error("http请求数据失败�?" + e.getMessage());
    }
    return jsonObject;
  }
Ejemplo n.º 22
0
 /**
  * GET请求
  *
  * @param url URL
  * @return 返回结果
  * @throws IOException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static String get(String url)
     throws IOException, NoSuchAlgorithmException, KeyManagementException {
   SSLContext ssl = SSLContext.getInstance("TLS");
   ssl.init(null, new TrustManager[] {trustManager}, null);
   HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("GET");
   conn.setSSLSocketFactory(ssl.getSocketFactory());
   BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
   String line = null;
   StringBuilder sb = new StringBuilder();
   while ((line = in.readLine()) != null) {
     sb.append(line);
   }
   conn.disconnect();
   return sb.toString();
 }
  private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
      throws IOException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);
    nection.setDoOutput(true);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
      nection.setRequestProperty("Authorization", "token " + accessToken);
    }

    OutputStream os = nection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(params.toString());
    writer.flush();
    writer.close();
    os.close();

    try {

      nection.connect();
      InputStream in = new BufferedInputStream(nection.getInputStream());
      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      StringBuilder response = new StringBuilder();
      while (true) {
        String line = reader.readLine();
        if (line == null) {
          break;
        }
        response.append(line);
      }

      try {
        return new JSONObject(response.toString());
      } catch (JSONException e) {
        throw new IOException(e);
      }

    } finally {
      nection.disconnect();
    }
  }
Ejemplo n.º 24
0
  /**
   * http post 请求
   *
   * @param url 请求url
   * @param jsonStr post参数
   * @return HttpResponse请求结果实例
   */
  public static Response httpPost(String url, String jsonStr) {
    Response response = null;

    HttpsURLConnection httpsURLConnection = null;
    try {
      URL urlObj = new URL(url);
      httpsURLConnection = (HttpsURLConnection) urlObj.openConnection();
      httpsURLConnection.setRequestMethod("POST");
      httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout);
      httpsURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
      httpsURLConnection.setDoOutput(true);
      httpsURLConnection.setChunkedStreamingMode(0);

      // start to post
      response = writeStream(httpsURLConnection, jsonStr);

      if (response == null) { // if post successfully

        response = readStream(httpsURLConnection);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (IOException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = new Response();
      response.content = ex.getMessage();
      response.code = -1;
    } finally {
      if (httpsURLConnection != null) httpsURLConnection.disconnect();
    }

    return response;
  }
  @Override
  public void run() {
    try {
      Thread.sleep(timeoutMillis);
    } catch (InterruptedException e) {
    }

    if (!cancelled) {
      if (httpsURLConnection != null) {
        httpsURLConnection.disconnect();
      } else if (httpURLConnection != null) {
        httpURLConnection.disconnect();
      }

      if (timeoutListener != null) {
        timeoutListener.notifyOnConnectionTimeout();
      }
    }
  }
Ejemplo n.º 26
0
  public static String SendGetHTTPS(final String url) throws Exception {

    HttpsURLConnection con = null;
    BufferedReader in = null;

    try {
      URL obj = new URL(url);
      con = (HttpsURLConnection) obj.openConnection();

      // optional default is GET
      con.setRequestMethod("GET");
      con.addRequestProperty("Content-Type", "application/json");

      // int responseCode = con.getResponseCode();

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

      String inputLine;
      StringBuffer response = new StringBuffer();

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

      // print result
      return response.toString();

    } catch (Exception e) {
      throw e;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e) {
        }
      }
      if (con != null) {
        con.disconnect();
      }
    }
  }
Ejemplo n.º 27
0
  public static Response getPayPalAccessToken() {

    Response response = null;

    HttpsURLConnection httpsURLConnection = null;
    try {
      URL urlObj = new URL(getPayPalAccessTokenUrl());
      httpsURLConnection = (HttpsURLConnection) urlObj.openConnection();
      httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout);
      httpsURLConnection.setRequestMethod("POST");
      httpsURLConnection.setRequestProperty("Accept", "application/json");
      httpsURLConnection.setRequestProperty(
          "Authorization",
          BCSecurityUtil.getB64Auth(
              BCCache.getInstance().paypalClientID, BCCache.getInstance().paypalSecret));
      httpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      httpsURLConnection.setDoOutput(true);
      httpsURLConnection.setChunkedStreamingMode(0);

      response = writeStream(httpsURLConnection, "grant_type=client_credentials");
      if (response == null) {

        response = readStream(httpsURLConnection);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (IOException e) {
      e.printStackTrace();
      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } finally {
      if (httpsURLConnection != null) httpsURLConnection.disconnect();
    }

    return response;
  }
Ejemplo n.º 28
0
  protected static String httpsPostImplement(String serviceURL, String postData)
      throws IOException {

    String dataBuff = "";

    URL postURL = new URL(serviceURL);
    HttpsURLConnection connection = (HttpsURLConnection) postURL.openConnection();
    connection.setRequestProperty("Accept-Language", "zh-tw,en-us;q=0.7,en;q=0.3");
    connection.connect();

    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    writer.writeBytes(postData);

    String lines;
    while ((lines = reader.readLine()) != null) {
      dataBuff = dataBuff + lines;
    }
    reader.close();

    connection.disconnect();
    return dataBuff;
  }
Ejemplo n.º 29
0
  /**
   * http get 请求
   *
   * @param url 请求uri
   * @return HttpResponse请求结果实例
   */
  public static Response httpGet(String url) {

    Response response = null;

    HttpsURLConnection httpsURLConnection = null;
    try {
      URL urlObj = new URL(url);
      httpsURLConnection = (HttpsURLConnection) urlObj.openConnection();
      httpsURLConnection.setConnectTimeout(BCCache.getInstance().connectTimeout);
      httpsURLConnection.setDoInput(true);

      response = readStream(httpsURLConnection);

    } catch (MalformedURLException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (IOException e) {
      e.printStackTrace();

      response = new Response();
      response.content = e.getMessage();
      response.code = -1;
    } catch (Exception ex) {
      ex.printStackTrace();
      response = new Response();
      response.content = ex.getMessage();
      response.code = -1;
    } finally {
      if (httpsURLConnection != null) httpsURLConnection.disconnect();
    }

    return response;
  }
Ejemplo n.º 30
0
  @SuppressWarnings("unchecked")
  public Object request(String method, String resource, Object parameters)
      throws VingdTransportException, VingdOperationException, IOException {
    URL url = new URL(backendURL + resource);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    method = method.toUpperCase();
    if (method.equals("GET") || method.equals("POST") || method.equals("PUT")) {
      conn.setRequestMethod(method);
    } else {
      throw new VingdTransportException("Unsupported HTTP method.", "Request");
    }

    byte[] credBytes = (username + ":" + pwhash).getBytes("ASCII");
    String credentials = DatatypeConverter.printBase64Binary(credBytes);
    conn.setRequestProperty("Authorization", "Basic " + credentials);
    conn.setRequestProperty("User-Agent", userAgent);

    if (parameters != null) {
      conn.setDoOutput(true);
      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      String parametersString = jsonStringify(parameters);
      writer.write(parametersString);
      writer.close();
    }

    int statusCode = 0;
    try {
      conn.connect();
      statusCode = conn.getResponseCode();
    } catch (IOException e) {
      throw new VingdTransportException("Connecting to Vingd Broker failed.", e);
    }

    StringBuffer response = new StringBuffer();
    String jsonContent;
    try {
      InputStreamReader reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
      BufferedReader in = new BufferedReader(reader);
      String line;
      while ((line = in.readLine()) != null) response.append(line);
      in.close();
      jsonContent = response.toString();
    } catch (IOException e) {
      throw new VingdTransportException("Communication with Vingd Broker failed.", e);
    } finally {
      conn.disconnect();
    }

    // return data response if request successful
    Map<String, Object> contentMap;
    try {
      contentMap = (Map<String, Object>) jsonParseMap(jsonContent);
    } catch (Exception e) {
      throw new VingdTransportException(
          "Non-JSON response or unexpected JSON structure.", "ParsingResponse", statusCode, e);
    }

    if (statusCode >= 200 && statusCode < 300) {
      Object data = contentMap.get("data");
      if (data == null) {
        throw new VingdTransportException("Invalid JSON error response.", "ParsingDataResponse");
      }
      return data;
    }

    // raise exception describing the vingd error condition
    String message, context;
    try {
      message = (String) contentMap.get("message");
      context = (String) contentMap.get("context");
    } catch (Exception e) {
      throw new VingdTransportException(
          "Invalid JSON error response.", "ParsingErrorResponse", statusCode, e);
    }
    throw new VingdOperationException(message, context, statusCode);
  }