在HttpClient调用其他项目接口时 传输JSON字符串中文乱码的问题

(初入行业小白  第一次发布文章 希望能帮到大家) 

我的代码结构是这样的  首先创建jsonObject对象设置数据 把jsonObject转换为String类型后 使用stringEntity.setContentEncoding("UTF-8");方法指定编码格式 但是在传输到另一个项目中时 JSON里的中文是乱码的 有类似情况的大佬们可以往下看

     //创建HttpClientTest
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建请求对象
        HttpPost httpPost = new HttpPost("http://******:****/******");
        //请求参数
        //将header和body组合到一个总的JSONObject中
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("header", header);
        jsonObject.put("body", body);

        String json = jsonObject.toString();
        StringEntity stringEntity = new StringEntity(json);
        //指定编码方式
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        //发送请求
        CloseableHttpResponse execute = httpClient.execute(httpPost);

后来查找资料发现 stringEntity.setContentEncoding("UTF-8");这个方法设置的编码格式是无效的 应该在这行代码之前 就指定编码格式才有用 修改后的代码是这样:

   // 将header和body组合到一个总的JSONObject中
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("header", header);
        jsonObject.put("body", body);

        String json = jsonObject.toString();
        StringEntity stringEntity = new StringEntity(json,"UTF-8");//加入编码格式
              
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        //发送请求
        CloseableHttpResponse execute = httpClient.execute(httpPost);

主要代码: StringEntity stringEntity = new StringEntity(json,"UTF-8");也就是在创建StringEntity对象时就需要指定编码格式  再传输数据就不乱码啦  

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值