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

情况

使用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"));

posted @ 2021-09-15 16:59  张占岭  阅读(235)  评论(0编辑  收藏  举报