httpclient 发送HTTP Post请求跳过与不跳过SSL认证

使用 apache httpclient 4.5.2

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>httpcore</artifactId>
        </exclusion>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
        <exclusion>
          <groupId>commons-codec</groupId>
          <artifactId>commons-codec</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

 发送HTTP Post请求跳过SSL认证:

public void test(){
  JSONObject requestJson = new JSONObject();
  requestJson.put("name", "zhang3");
  requestJson.put("age", 10);
  String requestParam = requestJson.toJSONString();
  String response = sendPostRequest("https://www.baidu.con", requestParam, "application/json; charset=UTF-8");
}

public static String sendPostRequest(String url, String params, String contentType){
        StringBuilder response = new StringBuilder();

        try {

            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                    .build();

            CloseableHttpClient httpClient = HttpClientBuilder.create()
                    .setSSLContext(sslContext)
                    .setConnectionManager(
                            new PoolingHttpClientConnectionManager(
                                    RegistryBuilder.<ConnectionSocketFactory>create()
                                            .register("http", PlainConnectionSocketFactory.INSTANCE)
                                            .register("https", new SSLConnectionSocketFactory(sslContext,
                                                    NoopHostnameVerifier.INSTANCE))
                                            .build()
                            ))
                    .build();

            HttpPost httpPost = new HttpPost(url);
//            //创建参数列表
//            List<NameValuePair> list = new ArrayList<>();
//            list.add(new BasicNameValuePair("j_username", "admin"));
//            list.add(new BasicNameValuePair("j_password", "admin"));
//            //url格式编码
//            UrlEncodedFormEntity params = new UrlEncodedFormEntity(list,StandardCharsets.UTF_8);
            StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
            httpPost.setHeader("Content-Type", contentType);
//            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(stringEntity);
            logger.info("POST 请求: {}", httpPost.getURI());
            logger.info("POST 请求参数: {}", EntityUtils.toString(stringEntity));
            //执行请求
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                HttpEntity entity = httpResponse.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                logger.info("响应:-------------------------------------------------------");
//                logger.info(response.toString());
            }
        } catch( IOException e){
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return response.toString();
    }

 发送HTTP Post请求不跳过SSL认证:

public void test(){
  JSONObject requestJson = new JSONObject();
  requestJson.put("name", "zhang3");
  requestJson.put("age", 10);
  String response = sendPostRequest("https://www.baidu.con", requestParam, "application/json; charset=UTF-8");
}

public static String sendPostRequest(String url, String params, String contentType){
        StringBuilder response = new StringBuilder();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            HttpPost httpPost = new HttpPost(url);
//            //创建参数列表
//            List<NameValuePair> list = new ArrayList<>();
//            list.add(new BasicNameValuePair("j_username", "admin"));
//            list.add(new BasicNameValuePair("j_password", "admin"));
//            //url格式编码
//            UrlEncodedFormEntity params = new UrlEncodedFormEntity(list,StandardCharsets.UTF_8);
            StringEntity stringEntity = new StringEntity(params, StandardCharsets.UTF_8);
            httpPost.setHeader("Content-Type", contentType);
//            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(stringEntity);
            logger.info("POST 请求: {}", httpPost.getURI());
            logger.info("POST 请求参数: {}", EntityUtils.toString(stringEntity));
            //执行请求
            try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                HttpEntity entity = httpResponse.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }

                logger.info("响应:-------------------------------------------------------");
//                logger.info(response.toString());
            }
        } catch( IOException e){
            e.printStackTrace();
        }
        return response.toString();
    }

 

posted @ 2022-12-06 08:02  锐洋智能  阅读(662)  评论(0编辑  收藏  举报