Exemplo n.º 1
1
  /**
   * @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();
  }
Exemplo n.º 2
0
  /**
   * Parses the url connection.
   *
   * @param url the url
   * @param apiKey the api key
   * @param requestMethod the request method
   * @param data the data
   * @return the string
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws JSONException the jSON exception
   */
  public static String parseUrlConnection(String url, String requestMethod, String data)
      throws IOException, JSONException {

    URL u = new URL(url);
    HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
    uc.setRequestMethod(requestMethod);
    String authentication =
        "<DocuSignCredentials><Username>"
            + Data.USERNAME
            + "</Username><Password>"
            + Data.PASSWORD
            + "</Password><IntegratorKey>"
            + Data.INTEGRATOR_KEY
            + "</IntegratorKey></DocuSignCredentials>";
    uc.setRequestProperty("X-DocuSign-Authentication", authentication);
    uc.setRequestProperty("Content-type", "application/json");
    uc.setRequestProperty("Accept", "application/json");
    if (data != null) {
      uc.setDoOutput(true);
      OutputStreamWriter postData = new java.io.OutputStreamWriter(uc.getOutputStream());
      postData.write(data);
      postData.flush();
      postData.close();
    }
    InputStream is = uc.getInputStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      return jsonText;
    } finally {
      is.close();
    }
  }
  @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);
  }
  /**
   * Synchronous call for logging in
   *
   * @param httpBody
   * @return The data from the server as a string, in almost all cases JSON
   * @throws MalformedURLException
   * @throws IOException
   * @throws JSONException
   */
  public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    HttpsURLConnection connection = createSecureConnection(url);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

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

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

    return response;
  }
Exemplo n.º 5
0
  // Add a new user
  public String addUser(String uri, String j) {
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setRequestMethod("POST");

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

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

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

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

      return "success";
    } catch (Exception e) {
      e.printStackTrace();
      return "fail";
    }
  }
Exemplo n.º 6
0
  public String doPost(String urlstr, byte data[]) throws IOException {
    URL url = new URL(urlstr);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    fetchReqMap(connection);
    //
    // connection.setRequestProperty("SOAPAction","https://hms.wellcare.cn:8443/services/EnergyData");

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

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

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

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

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

    return ret;
  }
 @Override
 public String receiveData(String urlPath, String streamData) {
   StringBuilder responseStringBuilder = new StringBuilder();
   URL url = null;
   URLConnection urlConnection = null;
   Scanner scanner = null;
   try {
     url = new URL(urlPath);
     urlConnection = url.openConnection();
     HttpsURLConnection httpsUrlConnection = (HttpsURLConnection) urlConnection;
     httpsUrlConnection.setDoOutput(true);
     httpsUrlConnection.setDoInput(true);
     httpsUrlConnection.setUseCaches(false);
     httpsUrlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
     httpsUrlConnection.setRequestMethod("POST");
     httpsUrlConnection.connect();
     if (streamData != null) {
       OutputStream outputStream = httpsUrlConnection.getOutputStream();
       OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
       outputStreamWriter.write(streamData);
       outputStreamWriter.flush();
       outputStreamWriter.close();
     }
     scanner = new Scanner(urlConnection.getInputStream(), "UTF-8");
     while (scanner.hasNext()) {
       String tempString = scanner.nextLine().trim();
       responseStringBuilder.append(tempString);
     }
     scanner.close();
   } catch (Exception e) {
     return null;
   }
   return responseStringBuilder.toString();
 }
Exemplo n.º 8
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;
    }
  }
  /**
   * Executa a operação da API informando um Builder para a requisição e resposta.
   *
   * @param requestBuilder é uma instância de {@link AkatusRequestBuilder} responsável pela criação
   *     do corpo da requisição.
   * @param responseBuilder é uma instância de {@link AkatusResponseBuilder} responsável pela
   *     criação do objeto que representa a resposta.
   * @return Uma instância de {@link AkatusResponse} com a resposta da operação.
   */
  public AkatusResponse execute(
      AkatusRequestBuilder requestBuilder, AkatusResponseBuilder responseBuilder) {

    AkatusResponse response = new AkatusResponse();

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

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

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

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

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

    return response;
  }
  public GetRecurringPaymentsProfileDetailsResposta getRecurringPaymentsProfileDetails(
      Map<String, String[]> parametros) throws IllegalStateException {

    StringBuilder param = new StringBuilder();
    GetRecurringPaymentsProfileDetailsResposta resp = null;

    try {
      HttpsURLConnection conn =
          Util.getConexaoHttps((String) parametros.get("NAOENVIAR_ENDPOINT")[0]);

      logger.info("Parametros da chamada GetRecurringPaymentsProfileDetails:");
      for (Map.Entry<String, String[]> item : parametros.entrySet()) {
        if (podeEnviarParametro(item.getKey(), item.getValue()[0])) {
          param.append(item.getKey() + "=" + URLEncoder.encode(item.getValue()[0], "UTF-8") + "&");
          logger.info("     " + item.getKey() + ": " + item.getValue()[0] + "&");
        }
      }

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
      logger.info("Chamada a: " + conn.getURL() + " com os parametros: " + param.toString());

      writer.write(param.toString());
      writer.flush();
      writer.close();

      InputStreamReader in = new InputStreamReader(conn.getInputStream());

      param = null;
      param = new StringBuilder();

      BufferedReader reader = new BufferedReader(in);

      String data;

      logger.info("Retorno da chamada: ");
      while ((data = reader.readLine()) != null) {
        param.append(data);
      }

      /*if (data.contains("TOKEN")) {
      param.append("==================================================");
      }*/

      data = param.toString();

      GetRecurringPaymentsProfileDetailsParser parser =
          GetRecurringPaymentsProfileDetailsParser.getInstance();
      resp = parser.parse(data);

      logger.info(data);

    } catch (IOException ex) {
      logger.fatal(
          "Erro ao executar GetRecurringPaymentsProfileDetails: " + ex.getLocalizedMessage(), ex);
    }

    return resp;
  }
  /**
   * Executa o metodo SetExpressCheckout
   *
   * @param parametros Parametros recebido do formulario ou do sistema do cliente
   */
  public SetExpressCheckoutResposta setExpressCheckout(Map<String, String[]> parametros)
      throws IllegalStateException {

    StringBuilder param = new StringBuilder();
    SetExpressCheckoutResposta resp = null;

    if (this.getCredenciais() == null) {
      throw new IllegalStateException("As credencais do merchant nao foram informadas.");
    }

    try {
      HttpsURLConnection conn =
          Util.getConexaoHttps((String) parametros.get("NAOENVIAR_ENDPOINT")[0]);

      logger.info("Parametros da chamada:");
      logger.info("Conectando-se a " + conn.getURL());
      for (Map.Entry<String, String[]> item : parametros.entrySet()) {
        if (podeEnviarParametro(item.getKey(), item.getValue()[0])) {
          param.append(item.getKey() + "=" + URLEncoder.encode(item.getValue()[0], "UTF-8") + "&");
          logger.info("     " + item.getKey() + ": " + item.getValue()[0] + "&");
        }
      }

      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
      // logger.info("Chamada: " + param.toString());

      writer.write(param.toString());
      writer.flush();
      writer.close();

      InputStreamReader in = new InputStreamReader(conn.getInputStream());

      param = null;
      param = new StringBuilder();

      BufferedReader reader = new BufferedReader(in);

      String data;

      logger.info("Retorno da chamada: ");
      while ((data = reader.readLine()) != null) {
        param.append(data);
      }

      data = param.toString();

      SetExpressCheckoutParser parser = SetExpressCheckoutParser.getInstance();
      resp = parser.parse(data);

      // logger.debug("Resposta do SetExpressCheckout: " + resp.toString());

    } catch (IOException ex) {
      logger.fatal("Erro ao executar SetExpressCheckout: " + ex.getLocalizedMessage(), ex);
    }

    return resp;
  }
Exemplo n.º 12
0
  public static String httsRequest(String url, String contentdata) {
    String str_return = "";
    SSLContext sc = null;
    try {
      sc = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {

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

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

    return str_return;
  }
Exemplo n.º 13
0
  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;
  }
Exemplo n.º 14
0
  /**
   * 发起https请求并获取结果
   *
   * @param requestUrl 请求地址
   * @param requestMethod 请求方式(GET、POST)
   * @param outputStr 提交的数据
   * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
   */
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    //
    log.info("https请求url是" + requestUrl);
    try {
      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());
      // 从上述SSLContext对象中得到SSLSocketFactory对象
      SSLSocketFactory ssf = sslContext.getSocketFactory();

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

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

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

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

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

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

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

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

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

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

    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchProviderException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return res;
  }
Exemplo n.º 16
0
  private void testIt() {

    String https_url = requestURL;
    URL url;

    SSLSocketFactory socketFactory = null;

    try {

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

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

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

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

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

      // dump all the content
      print_content(conn);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public boolean writeRequest(HttpsURLConnection connection, String textBody) {

    try {
      BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
      wr.write(textBody);
      wr.flush();
      wr.close();
      return true;
    } catch (IOException e) {
      return false;
    }
  }
Exemplo n.º 18
0
  public static String httpsRequestByWx(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
      // 创建SSLContext对象,并使用我们指定的信任管理器初始化
      TrustManager[] tm = {new MyX509TrustManager()};
      SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
      sslContext.init(null, tm, new java.security.SecureRandom());
      // 从上述SSLContext对象中得到SSLSocketFactory对象
      SSLSocketFactory ssf = sslContext.getSocketFactory();

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

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

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

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

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

      // 释放资源
      bufferedReader.close();
      inputStreamReader.close();
      inputStream.close();
      inputStream = null;
      conn.disconnect();
      jsonObject = JSONObject.fromObject(buffer.toString());
    } catch (ConnectException ce) {
      logger.error("连接超时:{}", ce);
    } catch (Exception e) {
      logger.error("https请求异常:{}", e);
    }
    return buffer.toString();
  }
Exemplo n.º 19
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;
  }
Exemplo n.º 20
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;
    }
  }
Exemplo n.º 21
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;
  }
Exemplo n.º 22
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());
    }
  }
Exemplo n.º 23
0
  public static Object ConnectToServer(
      URL url, String jsoninput, boolean hasinput, boolean hasoutput, String requestMethod) {
    try {
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setSSLSocketFactory(ssf);
      con.setDoInput(true);
      con.setRequestMethod(requestMethod);
      OutputStream os = null;
      StringBuffer sb = null;
      StringBuffer log = new StringBuffer();
      log.append(requestMethod).append(":");
      log.append("url=").append(url).append(".");

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

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

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

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
Exemplo n.º 24
0
  private static HttpsURLConnection sendSecureHttpsConnection(HttpsURLConnection conn, String data)
      throws IOException {
    BufferedWriter bw = null;
    try {
      conn.setDoOutput(true);

      bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
      bw.write(data);
      bw.flush();
      bw.close();

      return conn;
    } catch (IOException e) {
      log4j.error(e.getMessage(), e);
      throw e;
    }
  }
Exemplo n.º 25
0
  // Update a field in a record given REST URL
  public boolean updateField(String uri, String j) {
    try {
      URL url = new URL(uri);
      HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
      con.setDoOutput(true);
      con.setRequestMethod("PUT");

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

      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
      throws IOException {

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

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

    try {

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

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

    } finally {
      nection.disconnect();
    }
  }
Exemplo n.º 27
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;
  }
 public HttpsURLConnection post(String urlString, String params) {
   try {
     SSLSocketFactory sslFactory = getSSLSocketFactory(); // Custom method
     URL url = new URL(urlString);
     HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
     con.setSSLSocketFactory(sslFactory);
     con.setRequestMethod("POST");
     con.setDoInput(true);
     con.setDoOutput(true);
     OutputStream outStream = con.getOutputStream();
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream));
     writer.write(params);
     writer.flush();
     writer.close();
     return con;
   } catch (Exception e) {
     Log.i("SecureURLOpenException", e.getMessage());
   }
   return null;
 }
Exemplo n.º 29
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();
  }
Exemplo n.º 30
0
 /**
  * POST请求
  *
  * @param url URL
  * @param data 数据内容
  * @return 返回结果
  * @throws IOException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static String post(String url, String data)
     throws IOException, NoSuchAlgorithmException, KeyManagementException {
   SSLContext ssl = SSLContext.getInstance("TLS");
   ssl.init(null, new TrustManager[] {trustManager}, null);
   HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
   conn.setDoOutput(true);
   conn.setRequestMethod("POST");
   conn.setSSLSocketFactory(ssl.getSocketFactory());
   OutputStream out = conn.getOutputStream();
   out.write(data.getBytes("utf-8"));
   out.flush();
   out.close();
   BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
   String line = null;
   StringBuilder sb = new StringBuilder();
   while ((line = in.readLine()) != null) {
     sb.append(line);
   }
   conn.disconnect();
   return sb.toString();
 }