java~http獲取內存緩慢解決方法
情況
使用hutool的HttpUtil來獲取遠程的網(wǎng)頁,類似爬蟲,獲取到的內容是GBK的,我們把它直接使用response.charset("UTF-8");最后輸出body()之后發(fā)現(xiàn)是亂碼
工具
<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"));

浙公網(wǎng)安備 33010602011771號