今天用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

本文介绍了在JAVA使用httpclient发送json数据时遇到的中文乱码问题及其解决方案。通过分析代码,指出在new StringEntity时指定编码的重要性,以避免默认编码导致的乱码。提供了解决乱码的关键代码修改,包括在创建StringEntity时指定UTF-8编码。
最低0.47元/天 解锁文章
719

被折叠的 条评论
为什么被折叠?



