解决httpclient中文乱码

/ bug / 无站内评论 / 381浏览

乱码1

IOUtils.toString(httpClient.execute(new HttpGet(url)).getEntity().getContent());


乱码2

EntityUtils.toString(httpClient.execute(new HttpGet(url)).getEntity());


解决乱码

EntityUtils.toString(httpClient.execute(new HttpGet(url)).getEntity(), "UTF-8");


思路

在EntityUtils.toString源码中找到问题所在

/**
* Read the contents of an entity and return it as a String.
* The content is converted using the character set from the entity (if any),
* failing that, "ISO-8859-1" is used.
*
* @param entity the entity to convert to a string; must not be null
* @return String containing the content.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
* @throws UnsupportedCharsetException Thrown when the named charset is not available in
* this instance of the Java virtual machine
*/
public static String toString(final HttpEntity entity)
throws IOException, ParseException {
return toString(entity, (Charset)null);
}

toString有重载的方法,默认toString的方法使用默认的字符编码 “"ISO-8859-1" is used.”

召唤蕾姆
琼ICP备18000156号

鄂公网安备 42011502000211号