post方法请求乱码 ,在请求时设置body 为 “UTF-8” 即可
@Component
public class HttpUtil {
public static HttpUtil httpUtil;
private HttpClient httpClient = HttpClients.createDefault();
//双重锁
public static HttpUtil getInstance() {
if (httpUtil == null) {
synchronized (HttpUtil.class) {
if (httpUtil == null) {
httpUtil = new HttpUtil();
}
}
}
return httpUtil;
}
/**
* java发送raw
*/
public JSONObject httpRequest(String url,JSONObject json) {
JSONObject result = null;
try {
@SuppressWarnings({"resource"})
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json;charset=UTF-8");
*StringEntity entity = new StringEntity(json.toJSONString(),"UTF-8");*
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
String content = EntityUtils.toString(response.getEntity());
result = (JSONObject) JSONObject.parse(content);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
导入jar包:
<!--http请求客户端-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
请求方法为:
HttpUtil.getInstance().httpRequest(url,JsonObject);
|