今天用httpclient传输json数据,服务端接受数据 中文乱码,下面分别贴上修改前与修改后的代码以及原因分析
(1)修改前:
client端
public String sendHttpPost(String httpUrl, String data) {
// 创建post请求
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity entity;
try {
entity = new StringEntity(data);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
private String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
// 创建默认的httpclient实例
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Accept","aplication/json");
httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
// 执行请求
try {
logger.info("开始同步数据");
response = httpClient.execute(httpPost);
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
logger.info("数据同步结果:" + responseContent);
} catch (IOException e) {
logger.error("同步数据出错:" + e.toString());
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (Exception e2) {
logger.error("流关闭出错:" + e2.toString());
}
}
return responseContent;
}
(2)修改后
client端
public String sendHttpPost(String httpUrl, String data) {
// 创建post请求
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity entity;
entity = new StringEntity(data,"UTF-8");
entity.setContentType("application/json");
//entity.setContentType(new BasicH