HTTP请求返回结果乱码,设置UTF-8仍然不能解决?

处理HTTP请求返回结果时,出现乱码是由于Charset编码格式设置不正确,一般设置UTF-8能够解决大部分状况,但并非全部HTTP服务器都必定使用UTF-8格式,因此正确的方法是:
git


- 调用httpResponse.getEntiry()获取返回结果github

- 调用ContentType.get()获取内容类型服务器

- 调用ContentType.getCharset()获取编码格式ide

- 调用EntityUtils.toString()将返回结果格式化为字符串函数

public class RespStr implements ResponseHandler<String> {
    @Override
    public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
        HttpEntity entity = httpResponse.getEntity();
        ContentType contentType = ContentType.getOrDefault(entity);
        Charset charset = contentType.getCharset();
        return EntityUtils.toString(entity, charset);
    }
}编码


ResponseHandler<T>httpclient包内提供的接口,实现函数handleResponse()处理HTTP返回结果。spa


示例代码Github下载:https://github.com/jextop/StarterApi/接口

相关文章
相关标签/搜索