java~http獲(huo)取(qu)內存緩慢解決方法
情況
使用hutool的HttpUtil來獲取(qu)遠程的網(wang)頁,類似爬蟲,獲取(qu)到(dao)的內容是GBK的,我們把(ba)它直接使用response.charset("UTF-8");最后輸出body()之后發現是亂碼(ma)
工具
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.7</version>
</dependency>
解決
使(shi)用(yong)bodyBytes()先獲取到流,然后把它構建到一個(ge)字(zi)符串里,在構建時指定編碼(ma)類型,就可(ke)以解決了
- 直接指定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"));
