HttpClient在传参和返回结果的中文乱码问题


  我实例化一个StringEntiry,将json字符串写入请求体中。然后无论我以哪种编码方式输出StringEntity中的content,其中的中文均为乱码“???”。 这是怎么回事?

  总结:就是在传递的参数中设置,这个很重要

entity = new StringEntity(data,Charset.forName("UTF-8"));

  今天用httpclient传输json数据,服务端接受数据是中文乱码,原来还觉得应该是服务端程序处理字符编码的问题,后来用tcpdump抓包(tcpdump的相关内容可以参考:linux安装tcpdump),发现送到服务端时的报文已经是乱码,故可以百分百确定是我发送端的问题。

  经过分析验证,最终解决问题,特在此记录一下。

解决办法:
  发送端进行设置编码如下:

StringEntity s = new StringEntity(jsonStr, Charset.forName("UTF-8"));

  接收到响应的处理如下:

result = EntityUtils.toString(httpEntity, "UTF-8");// 返回json格式

完整代码如下:

/**
 * post请求
 * @param url
 * @param json
 * @return
 */
public static String httpPost(String url, String jsonStr) {
    
    String result = null;
    // 创建HttpClientBuilder  
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();  
    // HttpClient  
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    try {
        RequestConfig config = null;
        if (StringUtils.isNotEmpty(Constants.PROXY_IP) && Constants.PROXY_PORT > 0) {
            // 依次是代理地址,代理端口号,协议类型
            String agreement = url.substring(0, url.indexOf(":"));
            HttpHost proxy = new HttpHost(Constants.PROXY_IP, Constants.PROXY_PORT, agreement);
            config = RequestConfig.custom().setProxy(proxy).build();
        }
        // 请求地址  
        HttpPost httpPost = new HttpPost(url);
        if(config != null) {
            httpPost.setConfig(config);
        }
        //设置请求的报文头部的编码
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        //httpPost.setHeader(new BasicHeader("Content-Type", "application/json;charset=utf-8"));
        //设置期望服务端返回的编码
        httpPost.setHeader("Accept", "appliction/json");
        //httpPost.setHeader(new BasicHeader("Accept", "application/json"));
        
        StringEntity s = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json;charset=utf-8");//发送json数据需要设置contentType
        httpPost.setEntity(s);
        //执行请求
        HttpResponse response = closeableHttpClient.execute(httpPost);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
         //获得响应的实体对象
            HttpEntity httpEntity = response.getEntity();
            if(httpEntity != null) {
             //使用Apache提供的工具类进行转换成字符串
                result = EntityUtils.toString(httpEntity, "UTF-8");// 返回json格式
            }
        }
    }catch(Exception e) {
        logger.error("doPost请求异常,e:{}", e);
    }finally {
        // 释放资源  
        try {
            if(closeableHttpClient != null) {
                closeableHttpClient.close();
            }
        } catch (IOException e) {
            logger.error("关闭CloseableHttpClient异常,e:{}", e);
        } finally {
            closeableHttpClient = null;
        }
    }
    return result;
}

 

参考文章:https://blog.csdn.net/sdxushuxun/article/details/79282112

https://blog.csdn.net/xiaoyao8903/article/details/53244986/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM