(初入行业小白 第一次发布文章 希望能帮到大家)
我的代码结构是这样的 首先创建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对象时就需要指定编码格式 再传输数据就不乱码啦