JAVA发送json符号乱码,解决使用httpclient传递json数据乱码的问题

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值