使用httpclient发送post 请求json格式的参数获取返回值

参数是json格式的字符串的post请求:

private static String httpPost(String url, String body) throws Exception {
    // 1、创建一个htt客户端
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
    httpPost.setHeader("Accept", "application/json");
    httpPost.setEntity(new StringEntity(body, Charsets.UTF_8)); //json格式的字符{"username":"111","password":"111"}
    CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpPost);
    System.out.println(response.getStatusLine().getStatusCode() + "\n");
    HttpEntity entity = response.getEntity();
    String responseContent = EntityUtils.toString(entity, "UTF-8");
    response.close();
    httpClient.close();
    return responseContent;
}

值得注意的是:在调试中可能回遇到java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy 错误解决办法这样的问题

问题原因:pom文件中引用了较低版本的jar,TrustStrategy这个类找不到,经查看这个TrustStrategy位于org.apache.http.ssl.TrustStrategy包底下,属于httpcore-4.4.jar包底下,或者更高版本底下,而4.4以下的版本并没有这个类,所以产生这个错误的原因就是项目底下引用了低版本的httpcore的jar包,而这个httpcore的jar包又是跟httpclient的jar包相关联的,所以httpclient的jar包也要用较高版本。

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.3</version>
        </dependency>
解决方案:

       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.3</version>
        </dependency>

       <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.4</version>
        </dependency>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值