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/接口

相關文章
相關標籤/搜索