使用hutool的HttpUtil来获取远程的网页,类似爬虫,获取到的内容是GBK的,我们把它直接使用response.charset("UTF-8");最后输出body()之后发现是乱码

工具

 <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.5.7</version>
  </dependency>

解决

使用bodyBytes()先获取到流,然后把它构建到一个字符串里,在构建时指定编码类型,就可以解决了

  • 直接指定response的编码,未解决问题
 HttpResponse httpResponse = HttpUtil.createPost("xxx")
              .header("Content-Type", "application/json;charset:utf-8")
              .execute()
              .charset("UTF-8");
      System.out.println(httpResponse.body());
  • 使用bodyBytes()进行字符串构建,解决问题
HttpResponse response = HttpRequest.post(url)
        .header("connection", "keep-alive")
        .execute();

response.charset("utf-8");
log.info(new String(response.bodyBytes(), "UTF-8"));

java~http获取内存缓慢解决方法

相关文章:

  • 2021-07-24
  • 2021-07-02
  • 2021-11-26
  • 2021-08-01
  • 2021-12-02
  • 2022-01-21
  • 2022-12-23
猜你喜欢
  • 2021-07-21
  • 2021-08-15
  • 2022-12-23
  • 2021-06-13
  • 2021-04-23
  • 2021-09-03
  • 2022-12-23
相关资源
相似解决方案