public JSONObject speechToText(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;

    try {
      System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      // HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestMethod("POST");
      // conn.setRequestMethod("GET");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));
      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_CONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT)) {
        conn.setRequestProperty(
            "X-SpeechSubContext", (String) args.get(ATTConstant.ARG_HEADER_XSPEECH_SUBCONTEXT));
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty("Accept", (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      }

      String clientSdk =
          "ClientSdk=att_worklight-"
              + (String) args.get("platform")
              + "-"
              + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      String base64AudioString = (String) args.get(ATTConstant.ARG_FILEOBJECT);
      Logger logger = Logger.getLogger("Speech Adapter");
      logger.info("The received string is: " + base64AudioString);

      byte[] decoded = Base64.decode(base64AudioString);

      OutputStream wr = conn.getOutputStream();

      wr.write(decoded);
      wr.flush();
      wr.close();
      // System.out.println("********* Speech JAVA ADAPTER LOGS ***********");
      // System.out.println("Headers***********");
      // @SuppressWarnings("unchecked")
      // Map<String,List<String>> header = conn.getHeaderFields();
      // for (String key: header.keySet ())
      //   System.out.println (key+": "+conn.getHeaderField (key));

      JSONObject response = new JSONObject();
      if (conn.getResponseCode() < 400) {
        response = JSONObject.parse(conn.getInputStream());
      } else {
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }

      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message =
            url.toString() + " " + e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }

      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
  /**
   * 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 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("-------------------------------------");
      }
    }
  }
Ejemplo n.º 4
0
  /**
   * if the barcode hasn't already got a name on outpan.com the item will be listed online with the
   * passed name
   *
   * @param gtin
   * @param name
   */
  private void listNewItem(String gtin, String name) {
    try {
      URL url =
          new URL(
              "https://api.outpan.com/v2/products/"
                  + gtin
                  + "/name"
                  + "?apikey=e13a9fb0bda8684d72bc3dba1b16ae1e");

      HttpsURLConnection httpCon = (HttpsURLConnection) url.openConnection();
      httpCon.setDoOutput(true);
      httpCon.setRequestMethod("POST");

      // replaces umlauts, ß, ", ' and /
      name = IllegalStringReplacer.replaceIllegalChars(name);

      String content = "name=" + name;
      DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());

      out.writeBytes(content);
      out.flush();

      log.debug(httpCon.getResponseCode() + " - " + httpCon.getResponseMessage());
      out.close();

      if (httpCon.getResponseCode() == 200) {
        Alert alert =
            Alerter.getAlert(AlertType.INFORMATION, "Item Added", null, "Item is now listed.");
        alert.showAndWait();
        log.info("Item '" + name + "' now listed");

        addItem(gtin);
      } else {
        log.debug("Item could not be listed");
        Alert alert =
            Alerter.getAlert(
                AlertType.WARNING,
                "Item not Added",
                null,
                "Item could not be listed, please try again.");
        alert.showAndWait();
      }

    } catch (MalformedURLException e) {
      log.error("MalformedURLException: " + e.getMessage());
    } catch (IOException e) {
      log.error("IOException: " + e.getMessage());
    }
  }
Ejemplo n.º 5
0
  private void print_https_cert(HttpsURLConnection con) {

    if (con != null) {

      try {

        System.out.println("Response Code : " + con.getResponseCode());
        System.out.println("Cipher Suite : " + con.getCipherSuite());
        System.out.println("\n");

        Certificate[] certs = con.getServerCertificates();
        for (Certificate cert : certs) {
          System.out.println("Cert Type : " + cert.getType());
          System.out.println("Cert Hash Code : " + cert.hashCode());
          System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
          System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
          System.out.println("\n");
        }

      } catch (SSLPeerUnverifiedException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 6
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.º 7
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.º 8
0
  public void exec(HttpsCb cb) {

    try {
      if (!NetUtil.isConnected()) {
        ViewInject.toast("找不到网络了...");
        return;
      }
    } catch (Exception e) {
      return;
    }
    if (mSslContext == null) {
      try {
        mSslContext = initCertificate();
      } catch (Exception e) {
        e.printStackTrace();
        ViewInject.toast("init ssl failed");
        return;
      }
    }
    try {
      HttpsURLConnection conn = openConnection();
      int code = conn.getResponseCode();
      MLoger.debug("httpcode-->" + code);

      if (code == 200 || code == 201) { // 网络请求成功
        String data = parseResponse(conn.getInputStream());
        MLoger.debug("response data-->" + data);
        if (cb != null) cb.onResponse(data);
      } else {
        MLoger.debug("error httpcode-->" + code);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private String getHttpsCertificateInformation(HttpsURLConnection con) {
    if (con != null) {
      StringBuilder sb = new StringBuilder();
      try {
        sb.append("\nResponse Code : ");
        sb.append(con.getResponseCode());
        sb.append("\nCipher Suite : ");
        sb.append(con.getCipherSuite());
        sb.append("\n");

        Certificate[] certs = con.getServerCertificates();
        for (Certificate cert : certs) {
          sb.append("\nCert Type : ");
          sb.append(cert.getType());
          sb.append("\nCert Hash Code : ");
          sb.append(cert.hashCode());
          sb.append("\nCert Public Key Algorithm : ");
          sb.append(cert.getPublicKey().getAlgorithm());
          sb.append("\nCert Public Key Format : ");
          sb.append(cert.getPublicKey().getFormat());
          sb.append("\n");
        }

      } catch (IOException e) {
        return "Error while retrieving certificate information: " + e.getMessage();
      }

      return sb.toString();
    }
    return "Given connection was 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);
  }
Ejemplo n.º 11
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.º 12
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;
  }
Ejemplo n.º 13
0
  // return null means successfully write to server
  static Response writeStream(HttpsURLConnection connection, String content) {
    BufferedOutputStream out = null;
    Response response = null;
    try {
      out = new BufferedOutputStream(connection.getOutputStream());
      out.write(content.getBytes("UTF-8"));
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();

      try {
        // it could be caused by 400 and so on
        response = new Response();

        BufferedReader reader =
            new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));

        StringBuilder stringBuilder = new StringBuilder();

        int tmp;
        while ((tmp = reader.read()) != -1) {
          stringBuilder.append((char) tmp);
        }

        response.code = connection.getResponseCode();
        response.content = stringBuilder.toString();

      } catch (IOException e1) {
        response = new Response();
        response.content = e1.getMessage();
        response.code = -1;
        e1.printStackTrace();
      } catch (Exception ex) {
        // if user directly shutdowns network when trying to write to server
        // there could be NullPointerException or SSLException
        response = new Response();
        response.content = ex.getMessage();
        response.code = -1;
        ex.printStackTrace();
      }
    } finally {
      try {
        if (out != null) out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return response;
  }
  @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.º 15
0
  public static boolean verify(String gRecaptchaResponse) throws IOException {
    if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
      return false;
    }

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

      // add reuqest header
      con.setRequestMethod("POST");
      con.setRequestProperty("User-Agent", USER_AGENT);
      con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

      String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;

      // Send post request
      con.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(con.getOutputStream());
      wr.writeBytes(postParams);
      wr.flush();
      wr.close();

      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + url);
      System.out.println("Post parameters : " + postParams);
      System.out.println("Response Code : " + responseCode);

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

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

      // print result
      System.out.println(response.toString());

      // parse JSON response and return 'success' value
      JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
      JsonObject jsonObject = jsonReader.readObject();
      jsonReader.close();

      return jsonObject.getBoolean("success");
    } catch (Exception e) {
      return false;
    }
  }
  private String fetchMessages() throws Exception {
    String url = getAppBaseURL() + "fetch_messages";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();

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

    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
    return response.toString();
  }
Ejemplo n.º 17
0
  public ServiceUser authenticateOAuthCode(String code, String redirectUri) throws Exception {
    try {
      StringBuilder urlParamsBuilder = new StringBuilder(ACCESS_TOKEN_URL);
      urlParamsBuilder.append("?grant_type=authorization_code&code=");
      urlParamsBuilder.append(URLEncoder.encode(code));
      urlParamsBuilder.append("&client_id=");
      urlParamsBuilder.append(clientId);
      urlParamsBuilder.append("&client_secret=");
      urlParamsBuilder.append(clientSecret);
      urlParamsBuilder.append("&redirect_uri=");
      urlParamsBuilder.append(URLEncoder.encode(redirectUri));
      String urlParameters = urlParamsBuilder.toString();

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

      int responseCode = con.getResponseCode();
      log.debug("\nSending LinkedInd 'POST' request to URL : " + urlParameters);
      log.debug("Response Code : " + responseCode);

      // Read the stream and convert to JSON.
      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
      JsonParser parser = new JsonParser();
      JsonElement jsonRefreshTokenInfo = parser.parse(in);
      JsonObject jsonGroupObject = jsonRefreshTokenInfo.getAsJsonObject();
      JsonElement jsonAccessTokenElement = jsonGroupObject.get("access_token");
      // NOT USED - JsonElement jsonExpiresInElement = jsonGroupObject.get("expires_in");

      String accessToken = jsonAccessTokenElement.getAsString();
      // NOT USED - Long expiresIn = jsonExpiresInElement.getAsLong();
      String refreshToken = ""; // Not provided by LinkedIn

      ServiceUser serviceUser = getServiceUser(accessToken, refreshToken);

      return serviceUser;
    } catch (Exception e) {
      log.error("Unable to get authenticate oauth code", e);
      return null;
    }
  }
Ejemplo n.º 18
0
  public static String sendPost(String CaptchaResponse, String Secret) throws Exception {

    String url =
        "https://www.google.com/recaptcha/api/siteverify"
            + "?response="
            + CaptchaResponse
            + "&secret="
            + Secret;
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    // add reuqest header
    con.setRequestMethod("POST");

    String urlParameters = "";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    // System.out.println("\nSending 'POST' request to URL : " + url);
    // System.out.println("Response Code : " + responseCode);

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

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

    // print result
    System.out.println(response.toString());

    return response.toString();
  }
Ejemplo n.º 19
0
  /**
   * 处理https 只支持get
   *
   * @param uri 带https的网址
   * @param queryString get参数
   * @return 网络返回值
   */
  public String getHttps(String uri, String queryString) {

    if (!uri.endsWith("?")) {
      uri += "?";
    }
    uri += queryString;
    try {
      SSLContext sc = SSLContext.getInstance("TLS");

      sc.init(null, new TrustManager[] {new MyTrustManager()}, new SecureRandom());

      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

      HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());

      HttpsURLConnection con = (HttpsURLConnection) new URL(uri).openConnection();
      con.setRequestProperty("Connection", "Keep-Alive");
      con.setDoOutput(true);

      con.setDoInput(true);

      int rescode = con.getResponseCode();

      //			Log.d("TEST", "rescode"+rescode );
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

      StringBuffer sb = new StringBuffer();

      String line;

      while ((line = br.readLine()) != null) {
        sb.append(line);
      }
      return sb.toString();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  // Reads a response for a given connection and returns it as a string.
  public static String readResponse(HttpsURLConnection connection) {

    try {
      int responseCode = connection.getResponseCode();

      myprint("readResponse connection.getResponseCode()   " + responseCode);

      String jsonString = null;

      if (responseCode == HttpURLConnection.HTTP_OK) {

        InputStream linkinStream = connection.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int j = 0;

        while ((j = linkinStream.read()) != -1) {

          baos.write(j);
        }

        byte[] data = baos.toByteArray();

        jsonString = new String(data);
      }

      myprint("readResponse jsonString   " + jsonString);

      return jsonString.toString();

    } catch (IOException e) {

      e.printStackTrace();

      myprint("readResponse IOExceptionException   " + e);

      return new String();
    }
  }
Ejemplo n.º 21
0
 private boolean urlExists(String urlString) throws ProtocolException, IOException {
   if (urlString == null) return false;
   try {
     final URL url = new URL(urlString);
     int responseCode = 0;
     if (urlString.startsWith("https")) {
       // SSL
       HttpsURLConnection hc = (HttpsURLConnection) url.openConnection();
       hc.setRequestMethod("HEAD");
       responseCode = hc.getResponseCode();
     } else {
       // NO SSL
       HttpURLConnection hc = (HttpURLConnection) url.openConnection();
       hc.setRequestMethod("HEAD");
       responseCode = hc.getResponseCode();
     }
     return (responseCode == 200);
   } catch (MalformedURLException e) {
     LOG.debug(e.getMessage(), e);
   }
   return false;
 }
Ejemplo n.º 22
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 POST request
  public void sendPost(String url) throws Exception {

    // String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

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

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

    // print result
    System.out.println(response.toString());
  }
  @Test
  public void testTopPage() throws Exception {
    String url = getAppBaseURL();
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();

    // It ensures that our Application Default Credentials work well.
    assertEquals(200, responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
    String contents = response.toString();

    assertTrue(contents.contains(PROJECT_ID));
  }
Ejemplo n.º 25
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);
  }
  private void transfer(HttpsURLConnection conn, String filename) {
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {
      conn.setDoInput(true); // Allow Inputs
      conn.setDoOutput(true); // Allow Outputs
      conn.setUseCaches(false); // Don't use a Cached Copy
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

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

      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes(
          "Content-Disposition: form-data; name=\""
              + filename
              + "\";filename=\""
              + filename
              + "\""
              + lineEnd);

      dos.writeBytes(lineEnd);
      FileInputStream fileInputStream = this.context.openFileInput(filename);
      bytesAvailable = fileInputStream.available();

      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // read file and write it into form...
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      Log.v("mark", "reading " + bytesRead + " bytes");
      while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      // send multipart form data necesssary after file data...
      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      // Responses from the server (code and message)
      int serverResponseCode = conn.getResponseCode();
      String serverResponseMessage = conn.getResponseMessage();

      Log.v("mark", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
      fileInputStream.close();

      DataInputStream dis = new DataInputStream(conn.getInputStream());
      if (dis.available() > 0) {
        byte[] buf = new byte[256];
        dis.read(buf);
        Log.v("mark", "line1:" + new String(buf));
      } else {
        Log.v("mark", "line1:none");
      }

      // close the streams //
      //			if(dis.available()>0){
      //				byte[] buf = new byte[256];
      //				dis.read(buf);
      //				Log.v("mark","line2:"+new String(buf));
      //			}else{
      //				Log.v("mark","line2:none");
      //			}
      dis.close();
      dos.flush();
      dos.close();

    } catch (ProtocolException e) {
      Log.v("mark", "ProtocolException:" + e.getMessage());
    } catch (IOException e) {
      Log.v("mark", "IOException:" + e.getMessage());
    }
  }
Ejemplo n.º 27
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();
    }
  }
Ejemplo n.º 28
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();
    }
  }
Ejemplo n.º 29
0
  private void practice() {
    SimpleDateFormat date_format = new SimpleDateFormat("yyyy MMM dd HH:mm z", Locale.ENGLISH);

    String location = "40.77,-73.77";

    String url =
        "https://maps.googleapis.com/maps/api/timezone/json?location=" + location + "&timestamp=";
    try {
      Date date =
          //					new Date();
          (Date) date_format.parse("2015 Feb 10 10:47 GMT");
      System.out.println(date.getTime() / 1000);
      System.out.println(date.toString());

      url += "" + date.getTime() / 1000;
      URL u = new URL(url);
      u =
          new URL(
              "https://maps.googleapis.com/maps/api/timezone/json?location=39.053528,-84.66307&timestamp=1423565220");

      URL u2 =
          new URL(
              "http://api.timezonedb.com/?lat=40.7833&lng=-73.75&format=json&key=NMBW9G7ILB6H&timestamp=1418208420");
      HttpsURLConnection connection = (HttpsURLConnection) u.openConnection();
      //			HttpURLConnection connection = (HttpURLConnection) u2.openConnection();

      connection.setRequestMethod("GET");

      int responseCode = connection.getResponseCode();

      if ((responseCode >= 200) && (responseCode <= 299)) {
        InputStream is = connection.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder str = new StringBuilder();
        String line = "";

        while ((line = reader.readLine()) != null) {
          str.append(line);
        }

        JSONObject obj = new JSONObject(str.toString());
        //				System.out.println(obj.get("status"));
        //				System.out.println(obj.get("abbreviation"));
        System.out.println(obj.getString("timeZoneName"));
        System.out.println(obj.getLong("dstOffset"));

        //				String timezone = obj.getString("zoneName");
        //				String[] sArray = timezone.split(" ");
        //				int length = 0;
        //				String acronym = "";
        //				while(length<sArray.length){
        //					acronym += sArray[length].charAt(0);
        //					length++;
        //				}
        //				long offset =
        //						(obj.getInt("dst")-1)*3600 +
        //						obj.getLong("gmtOffset");

        Date da2 = new Date();
        da2.setTime(date.getTime() + (obj.getLong("dstOffset") + obj.getLong("rawOffset")) * 1000);
        //				date.setMonth(5);
        //				System.out.println(acronym);

        System.out.println(da2.toGMTString());
        System.out.println(date.toString());
      }

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 30
0
 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();
     }
   }
 }