解决方案
设定编码方式
/**
* 发送请求
* @param url
* @param json
* @return
* @throws Exception
*/
public String testPOST(String url,String json) throws Exception{
// 创建httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建请求对象
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(json,"utf-8"));
//发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//解析返回结果
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity returnEntity = response.getEntity();
String body = EntityUtils.toString(returnEntity);
log.info("状态码:{}",statusCode);
log.info("响应参数:{}",body);
//关闭资源
response.close();
httpClient.close();
return body;
}
注意事项
14行中如果不使用构造器进行对象创建
使用空参构造器创建对象,再去使用set去设定参数会导致发送请求,解析?乱码占位问题
自己笔记发送post请求和get请求的实例代码链接
https://www.yuque.com/riyeqiaodaimadelong/alyggg/kdtnmshrmpzh5abu
依赖
HttpClient
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
JSON依赖
<!--JSON依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.32</version>
</dependency>