httpclient、hutool(发送HTTP请求)

使用 hutool

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.16</version>
        </dependency>

使用 cn.hutool.http.HttpRequest 对象默认跳过 SSL 验证

  public void test(){
    JSONObject requestJson = new JSONObject();
    requestJson.put("name", "zhang3");
    requestJson.put("age", 10);
    String requestParam = requestJson.toJSONString();
    HttpResponse responseObj = HttpRequest.post("https://www.baidu.com").body(requestParam).execute();
  }

使用 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();
    }



作者:Wilson_z
链接:https://www.jianshu.com/p/6ceee895b65b
来源:简书

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值