/**
   * @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
 /**
  * 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;
 }
 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;
 }
  /**
   * 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();
      }
    }
  }
  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;
  }
  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("-------------------------------------");
      }
    }
  }
    // 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;
    }
    private String downloadUrl(String urlString)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException,
            CertificateException {

      HostnameVerifier hostnameVerifier =
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
              return hv.verify("localhost", session);
            }
          };
      URL url = new URL(urlString);
      HttpsURLConnection conn = null;
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in =
          activity.getApplicationContext().getResources().openRawResource(R.raw.mykeystore);
      try {
        // Initialize the keystore with the provided trusted
        // certificates
        // Also provide the password of the keystore
        trusted.load(in, "my_password".toCharArray());
      } finally {
        in.close();
      }
      String algorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
      tmf.init(trusted);

      SSLContext context = SSLContext.getInstance("TLS");
      context.init(null, tmf.getTrustManagers(), null);

      conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(hostnameVerifier);
      conn.setSSLSocketFactory(context.getSocketFactory());
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.setRequestProperty("Accept", "text/xml");
      conn.setRequestProperty(
          "Authorization",
          "Basic "
              + Base64.encodeToString(
                  ((this.userName + ":" + this.passWord).getBytes()), Base64.NO_WRAP));
      // Starts the query
      conn.connect();
      return conn.getResponseMessage();
    }
  @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;
  }
示例#10
0
  public HttpsURLConnection openConnection() throws IOException {
    HttpsURLConnection connection = null;

    try {

      if (!isPost) { // 如果是get请求则拼接URL地址,一般情况下不会走https的get请求
        mUrl += packageTextParamsForGet();
      }
      // 初始化连接
      URL connecter = new URL(mUrl);
      connection = (HttpsURLConnection) connecter.openConnection();
      // 设置安全套接工厂

      connection.setSSLSocketFactory(mSslContext.getSocketFactory());
      connection.setConnectTimeout(TIME_OUT);
      connection.setReadTimeout(TIME_OUT);
      // connection.setRequestProperty("User-Agent",
      // "Mozilla/5.0 ( compatible ) ");
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Content-Type", "*/*;charset=UTF-8");
      connection.setRequestProperty("Connection", "Keep-Alive");
      if (isPost) {
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(false);
      }
      // 设置输入输出流
      connection.setDoInput(true);
      if (isPost) connection.setDoOutput(true);

    } catch (IOException ioe) {
      throw ioe;
    }
    // 查询params里面是否有数据
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : mParams.entrySet())
      sb.append(entry.getValue() + LINE_END);
    // 向输入流里面写入,需要提交的数据
    out.write(sb.toString().getBytes());
    out.flush();
    out.close();
    return connection;
  }
  /**
   * 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;
  }
示例#12
0
  private static HttpsURLConnection fetchConnection(String apiURL, int timeout, Proxy proxy)
      throws MalformedURLException, IOException, ProtocolException {
    HttpsURLConnection connection;
    URL hostURL = new URL(apiURL);
    if (proxy == null) {
      connection = (HttpsURLConnection) hostURL.openConnection();
    } else {
      connection = (HttpsURLConnection) hostURL.openConnection(proxy);
    }

    // This actually turns into a POST since we are writing to the
    // resource body. ( You can see this in Webscarab or some other HTTP
    // interceptor.
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(timeout);
    connection.setReadTimeout(timeout);
    connection.setDoOutput(true);
    connection.setDoInput(true);

    return connection;
  }
  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;
  }
示例#14
0
  public static String performHttpsGet(String url) {
    try {
      HttpsURLConnection c = (HttpsURLConnection) new URL(url).openConnection();
      c.setConnectTimeout(5000);
      c.setReadTimeout(5000);
      c.setDoInput(true);
      if (c.getResponseCode() != 200) {
        return null;
      }

      byte[] buf = reusableBuffers.get();
      StringBuilder builder = new StringBuilder();

      int amount;
      while ((amount = c.getInputStream().read(buf)) > 0) {
        builder.append(new String(buf, 0, amount));
      }

      return builder.toString();
    } catch (Exception e) {
      return null;
    }
  }
  /**
   * 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;
  }
示例#16
0
  public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    BeeboApplication globalContext = BeeboApplication.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      URL url = new URL(urlAddress);
      Proxy proxy = getProxy();
      HttpsURLConnection uRLConnection;
      if (proxy != null) {
        uRLConnection = (HttpsURLConnection) url.openConnection(proxy);
      } else {
        uRLConnection = (HttpsURLConnection) url.openConnection();
      }

      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
      uRLConnection.setReadTimeout(READ_TIMEOUT);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.connect();

      DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
      out.write(Utility.encodeUrl(param).getBytes());
      out.flush();
      out.close();
      return handleResponse(uRLConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
示例#17
0
  @Override
  protected XrayUpdater.CheckResult doInBackground(Void... v) {
    HttpsURLConnection urlConnection = null;
    InputStream inputStream = null;
    XrayUpdater.CheckResult result = XrayUpdater.CheckResult.UP_TO_DATE;

    Log.d(TAG, "Attempting to fetch manifest...");

    try {
      // issue a GET request to determine the latest available apk version
      URL url = new URL(XrayUpdater.VERSION_URL);
      urlConnection =
          PinningHelper.getPinnedHttpsURLConnection(context, XrayUpdater.CERT_PINS, url);
      urlConnection.setConnectTimeout(XrayUpdater.CONNECTION_TIMEOUT);
      urlConnection.setReadTimeout(XrayUpdater.READ_TIMEOUT);
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoInput(true);
      urlConnection.connect();

      int responseCode = urlConnection.getResponseCode();
      int apkVersion = -1;
      String apkName = null;
      String apkChecksum = null;

      // read the results into a byte array stream
      inputStream = new BufferedInputStream(urlConnection.getInputStream());
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      if (responseCode != HttpURLConnection.HTTP_OK) {
        Log.d(TAG, "Error fetching app version, HTTP request returned: " + responseCode);
      } else if (!XrayUpdater.writeToOutputStream(inputStream, byteStream)) {
        Log.d(TAG, "Error fetching app version, invalid input stream");
      } else {
        // request looks okay, let's verify response signature
        Signature ecdsaSignature =
            Signature.getInstance(XrayUpdater.ECDSA_ALGORITHM, XrayUpdater.ECDSA_PROVIDER);
        PublicKey extPubKey = crypto.readPublicKey(XrayUpdater.SERVER_PUB_KEY);
        ecdsaSignature.initVerify(extPubKey);
        ecdsaSignature.update(byteStream.toByteArray());

        String signature = urlConnection.getHeaderField("Xray-Signature");
        byte[] signature_bytes = crypto.base64Decode(signature);

        if (!ecdsaSignature.verify(signature_bytes)) {
          Log.d(TAG, "Invalid signature");
        } else {
          Log.d(TAG, "Signature valid. Reading JSON response...");

          // signature is valid, so read version and filename from JSON response
          inputStream = new ByteArrayInputStream(byteStream.toByteArray());
          JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
          reader.beginObject();
          while (reader.hasNext()) {
            String key = reader.nextName();
            if (key.equals("apkVersion")) {
              apkVersion = Integer.parseInt(reader.nextString());
            } else if (key.equals("apkName")) {
              apkName = reader.nextString();
            } else if (key.equals("apkChecksum")) {
              apkChecksum = reader.nextString();
            } else {
              reader.skipValue();
            }
          }
          reader.endObject();
        }
      }

      if (apkVersion < 0 || apkName == null || apkChecksum == null) {
        Log.d(TAG, "Error fetching app version, JSON response missing fields");
      } else if (apkVersion == BuildConfig.VERSION_CODE) {
        Log.d(TAG, "Already up to date");
      } else { // out of date
        XrayUpdater.setSharedPreference("apkName", apkName);
        XrayUpdater.setSharedPreference("apkChecksum", apkChecksum);
        result = XrayUpdater.CheckResult.OUT_OF_DATE;
      }
    } catch (MalformedURLException e) {
      Log.d(TAG, "Found malformed URL when trying to update");
    } catch (SocketTimeoutException e) {
      Log.d(TAG, "Socket timed out when trying to update: " + e.toString());
    } catch (SSLHandshakeException e) {
      Log.d(TAG, "Failed SSL Handshake when trying to update: " + e.toString());
      result = XrayUpdater.CheckResult.SSL_ERROR;
    } catch (IOException e) {
      Log.d(TAG, "Found IO exception when trying to update: " + e.toString());
    } catch (Exception e) {
      Log.d(TAG, "Received error when trying to update: " + e.toString());
    } finally {
      Log.d(TAG, "Cleaning up check task...");

      // close the GET connection
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          Log.d(TAG, "Found IO exception when trying to close inputstream: " + e.toString());
        }
      }
      if (urlConnection != null) {
        urlConnection.disconnect();
      }

      Log.d(TAG, "Exiting check task");
    }
    return result;
  }
示例#18
0
    // HTTP PUT change to the server
    // Return 0 on success
    // Return 1 on Android failure
    // Return 2 on server failure
    private void updateItem() {
      URL url;
      HttpsURLConnection urlConnection = null;
      int size;
      byte[] data;
      OutputStream out;
      String itemUrl = UPDATE_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");

        // To upload data to a web server, configure the connection for output using
        // setDoOutput(true). It will use POST if setDoOutput(true) has been called.
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("PUT");

        // Convert item to JSON string
        JSONObject jsonItem = new JSONObject();
        JSONObject jsonMember = new JSONObject();
        JSONArray jsonMembers = new JSONArray();
        jsonMember.put("attendant", change);
        if (change >= 1 && mPhoneNumber != null && !mPhoneNumber.isEmpty()) {
          jsonMember.put("phonenumber", mPhoneNumber);
        }
        jsonMembers.put(jsonMember);
        jsonItem.put("members", jsonMembers);
        data = jsonItem.toString().getBytes();

        // For best performance, you should call either setFixedLengthStreamingMode(int) when the
        // body length is known in advance, or setChunkedStreamingMode(int) when it is not.
        // Otherwise HttpURLConnection will be forced to buffer the complete request body in memory
        // before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
        size = data.length;
        if (size > 0) {
          urlConnection.setFixedLengthStreamingMode(size);
        } else {
          // Set default chunk size
          urlConnection.setChunkedStreamingMode(0);
        }

        // Get the OutputStream of HTTP client
        out = new BufferedOutputStream(urlConnection.getOutputStream());
        // Copy from file to the HTTP client
        out.write(data);
        // Make sure to close streams, otherwise "unexpected end of stream" error will happen
        out.close();

        // Check canceled
        if (isCancelled()) {
          Log.d(LOG_TAG, "Updating item canceled");
          status = UpdateItemStatus.ANDROID_FAILURE;
          return;
        }

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

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

        // 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;
        }
        if (responseCode != HttpURLConnection.HTTP_OK) {
          Log.d(LOG_TAG, "Update item attendant " + change + " failed");
          status = UpdateItemStatus.SERVER_FAILURE;
          return;
        }

        // Vernon debug
        Log.d(LOG_TAG, "Update item attendant " + change + " successfully");

      } catch (Exception e) {
        e.printStackTrace();
        Log.d(LOG_TAG, "Update item failed because " + e.getMessage());
        status = UpdateItemStatus.ANDROID_FAILURE;
      } finally {
        if (urlConnection != null) {
          urlConnection.disconnect();
        }
      }
    }
示例#19
0
  /**
   * Realiza una peticción https GET utilizando el proxy especificado (con certificado)
   *
   * @param sUrl Dirección http a resolver
   * @param sProxy Nombre del proxy, p.e. proxy.bde.es
   * @param sProxyPort Puerto del proxy, p.e. 80
   * @return String con el texto devuelto
   * @throws MalformedURLException
   * @throws IOException
   */
  public static String httpsGetCertificado(
      String sUrl,
      String sProxy,
      String sProxyPort,
      int timeoutMs,
      String alias,
      String keyStore,
      String trustStore,
      String keyStorePassword,
      String trustStorePassword,
      String pCookies,
      int numeroDeRedireccionActual)
      throws MalformedURLException, IOException {

    try {
      SSLSocketFactory sc =
          new SSLSocketFactoryGenerator(
                  alias, keyStore, trustStore, keyStorePassword, trustStorePassword)
              .getSSLSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory(sc);

    } catch (Exception e) {

      return null;
    }

    HttpsURLConnection con = null;
    URL url = new URL(sUrl);

    // Creamos la conexión con la url
    if (sProxy != null && sProxyPort != null) {
      Proxy proxy =
          new Proxy(Proxy.Type.HTTP, new InetSocketAddress(sProxy, Integer.parseInt(sProxyPort)));

      con = (HttpsURLConnection) url.openConnection(proxy);
    } else {
      con = (HttpsURLConnection) url.openConnection();
    }

    // Evitamos que se sigan los redirects ya que los redirects los hace sin
    // pasar las cookies lo cual es un bug.
    con.setInstanceFollowRedirects(false);
    // Evitamos el uso de respuestas cacheadas
    con.setUseCaches(false);

    // Fijamos los timeouts
    if (timeoutMs > 0) {
      con.setConnectTimeout(timeoutMs);
      con.setReadTimeout(timeoutMs);
    }
    // Respuesta de la petición
    con.connect();

    InputStream in = con.getInputStream();
    StringBuffer sb = new StringBuffer();

    int c;
    while ((c = in.read()) != -1) sb.append((char) c);
    int responseCode = con.getResponseCode();
    String cookies = HttpUtil.getResponseHeader((URLConnection) con, "Set-Cookie");
    if (!StringUtils.isEmpty(pCookies) && !StringUtils.isEmpty(cookies)) {
      cookies = pCookies + "; " + cookies;
    }
    String location = HttpUtil.getResponseHeaderLocation(sUrl, (URLConnection) con);
    con.disconnect();

    // Comprobación de si es una redirección
    if (responseCode == 301 || responseCode == 302) {
      if (numeroDeRedireccionActual < 10) {
        return httpsGetCertificado(
            location,
            sProxy,
            sProxyPort,
            timeoutMs,
            alias,
            keyStore,
            trustStore,
            keyStorePassword,
            trustStorePassword,
            cookies,
            numeroDeRedireccionActual + 1);
      } else {
        throw new IOException(
            "Se han producido 10 redirecciones consecutivas al solicitar la página web. Se cancela la petición");
      }
    } else {
      return sb.toString();
    }
  }
示例#20
0
  /**
   * Realiza una peticción https GET utilizando el proxy especificado
   *
   * @param sUrl Dirección http a resolver
   * @param sProxy Nombre del proxy, p.e. proxy.bde.es
   * @param sProxyPort Puerto del proxy, p.e. 80
   * @return String con el texto devuelto
   * @throws MalformedURLException
   * @throws IOException
   */
  public static String httpsGet(
      String sUrl,
      String sProxy,
      String sProxyPort,
      int timeoutMs,
      String pCookies,
      int numeroDeRedireccionActual)
      throws MalformedURLException, IOException {

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts =
        new TrustManager[] {
          new X509TrustManager() {

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
              return null;
            }

            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {}
          }
        };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new java.security.SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {

      return null;
    }

    HttpsURLConnection con = null;
    URL url = new URL(sUrl);

    // Creamos la conexión con la url
    if (sProxy != null && sProxyPort != null) {
      Proxy proxy =
          new Proxy(Proxy.Type.HTTP, new InetSocketAddress(sProxy, Integer.parseInt(sProxyPort)));

      con = (HttpsURLConnection) url.openConnection(proxy);
    } else {
      con = (HttpsURLConnection) url.openConnection();
    }

    // Evitamos que se sigan los redirects ya que los redirects los hace sin
    // pasar las cookies lo cual es un bug.
    con.setInstanceFollowRedirects(false);
    // Evitamos el uso de respuestas cacheadas
    con.setUseCaches(false);

    // Fijamos los timeouts
    if (timeoutMs > 0) {
      con.setConnectTimeout(timeoutMs);
      con.setReadTimeout(timeoutMs);
    }

    // Enviamos las cookies
    if (!StringUtils.isEmpty(pCookies)) {
      con.setRequestProperty("Cookie", pCookies);
    }

    // Respuesta de la petición
    con.connect();

    InputStream in = con.getInputStream();
    StringBuffer sb = new StringBuffer();

    int c;
    while ((c = in.read()) != -1) sb.append((char) c);

    int responseCode = con.getResponseCode();
    String cookies = HttpUtil.getResponseHeader((URLConnection) con, "Set-Cookie");
    if (!StringUtils.isEmpty(pCookies) && !StringUtils.isEmpty(cookies)) {
      cookies = pCookies + "; " + cookies;
    }
    String location = HttpUtil.getResponseHeaderLocation(sUrl, (URLConnection) con);
    con.disconnect();

    // Comprobación de si es una redirección
    if (responseCode == 301 || responseCode == 302) {
      if (numeroDeRedireccionActual < 10) {
        Logger.getRootLogger().debug("Redirigiendo a " + location);
        Logger.getRootLogger().debug("Cookies enviadas:" + cookies);
        return httpsGet(
            location, sProxy, sProxyPort, timeoutMs, cookies, numeroDeRedireccionActual);
      } else {
        throw new IOException(
            "Se han producido 10 redirecciones consecutivas al solicitar la página web. Se cancela la petición");
      }
    } else {
      return sb.toString();
    }
  }
 public void recursiveRequest(String path, String reffer) {
   URL url = null;
   try {
     url = new URL(path);
     conn = (HttpsURLConnection) url.openConnection();
     // 同步接口获取IP
     String ip = httpdns.getIpByHostAsync(url.getHost());
     if (ip != null) {
       // 通过HTTPDNS获取IP成功,进行URL替换和HOST头设置
       Log.d(TAG, "Get IP: " + ip + " for host: " + url.getHost() + " from HTTPDNS successfully!");
       String newUrl = path.replaceFirst(url.getHost(), ip);
       conn = (HttpsURLConnection) new URL(newUrl).openConnection();
       // 设置HTTP请求头Host域
       conn.setRequestProperty("Host", url.getHost());
     }
     conn.setConnectTimeout(30000);
     conn.setReadTimeout(30000);
     conn.setInstanceFollowRedirects(false);
     TlsSniSocketFactory sslSocketFactory = new TlsSniSocketFactory(conn);
     conn.setSSLSocketFactory(sslSocketFactory);
     conn.setHostnameVerifier(
         new HostnameVerifier() {
           /*
            * 关于这个接口的说明,官方有文档描述:
            * This is an extended verification option that implementers can provide.
            * It is to be used during a handshake if the URL's hostname does not match the
            * peer's identification hostname.
            *
            * 使用HTTPDNS后URL里设置的hostname不是远程的主机名(如:m.taobao.com),与证书颁发的域不匹配,
            * Android HttpsURLConnection提供了回调接口让用户来处理这种定制化场景。
            * 在确认HTTPDNS返回的源站IP与Session携带的IP信息一致后,您可以在回调方法中将待验证域名替换为原来的真实域名进行验证。
            *
            */
           @Override
           public boolean verify(String hostname, SSLSession session) {
             String host = conn.getRequestProperty("Host");
             if (null == host) {
               host = conn.getURL().getHost();
             }
             return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
           }
         });
     int code = conn.getResponseCode(); // Network block
     if (needRedirect(code)) {
       // 临时重定向和永久重定向location的大小写有区分
       String location = conn.getHeaderField("Location");
       if (location == null) {
         location = conn.getHeaderField("location");
       }
       if (!(location.startsWith("http://") || location.startsWith("https://"))) {
         // 某些时候会省略host,只返回后面的path,所以需要补全url
         URL originalUrl = new URL(path);
         location = originalUrl.getProtocol() + "://" + originalUrl.getHost() + location;
       }
       recursiveRequest(location, path);
     } else {
       // redirect finish.
       DataInputStream dis = new DataInputStream(conn.getInputStream());
       int len;
       byte[] buff = new byte[4096];
       StringBuilder response = new StringBuilder();
       while ((len = dis.read(buff)) != -1) {
         response.append(new String(buff, 0, len));
       }
       Log.d(TAG, "Response: " + response.toString());
     }
   } catch (MalformedURLException e) {
     Log.w(TAG, "recursiveRequest MalformedURLException");
   } catch (IOException e) {
     Log.w(TAG, "recursiveRequest IOException");
   } catch (Exception e) {
     Log.w(TAG, "unknow exception");
   } finally {
     if (conn != null) {
       conn.disconnect();
     }
   }
 }