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

寿浩言
2023-12-01

参数是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>

 类似资料: