接口请求 - HttpClient 发起请求返回结果中文乱码

时间 2021/2/23 17:02:26 加载中...

问题

使用 Java 中的 HttpClients 调用第三方的一个接口,返回的内容中,部分中文乱码(我碰到的问题还不是中文全部乱码)

图片:

当时的转换代码为:

  1. /**
  2. * 将返回结果转化为String
  3. *
  4. * @param entity
  5. * @return
  6. * @throws Exception
  7. */
  8. private static String getRespString(HttpEntity entity) throws Exception {
  9. if (entity == null) {
  10. return null;
  11. }
  12. InputStream is = entity.getContent();
  13. StringBuffer strBuf = new StringBuffer();
  14. byte[] buffer = new byte[4096];
  15. int r = 0;
  16. while ((r = is.read(buffer)) > 0) {
  17. //strBuf.append(new String(buffer, 0, r, "GB2312"));
  18. //strBuf.append(new String(buffer, 0, r, "GBK"));
  19. strBuf.append(new String(buffer, 0, r, "UTF-8"));
  20. }
  21. return strBuf.toString();
  22. }

虽然已经明确使用了 UTF-8 编码,但还是出现了部分乱码的情况。

分析

使用 Postman 测试了返回的内容,结果没有乱码。这就说明接口返回的没有问题。

解决

使用其自带的工具类替代了 HttpEntity 到字符串的转换

  1. import org.apache.http.util.EntityUtils;
  2. String respStr = EntityUtils.toString(resEntity);
扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/httpclients-chinese-garbled.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。