采用httpClient通过post方式发送json数据时遇到响应是乱码的问题,返回的响应中文部分是乱码,发送端原代码如下:
public static void sendJsonByPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "xxx";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.setHeader("Accept","application/json");
JSONObject j = new JSONObject();
j.put("key", "value");
StringEntity se = new StringEntity(j.toString());
se.setContentType("text/json");
httpPost.setEntity(se);
HttpResponse response=httpClient.execute(httpPost);
if(response != null && response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.parseObject(result);
}
}
获取到result之后发现响应里中文部分是乱码,分析发现是此句话:
String result = EntityUtils.toString(response.getEntity());
在toString的时候未指定字符集引起,因接收端采用的utf-8,遂将上述代码改为:
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
修改后返回结果中无乱码。
此方法仅适用于此种响应结果EntityUtils转字符串时出现中文乱码的情况,若为post请求参数中存在中文导致的乱码需要另外讨论解决。
--end--