接入百度AI語音識別雲服務時踩到的一個坑,ContentType讀取不到Charset

緣由:不是全部Web服務器都正確返回了內容編碼格式,那就再增長一個錯誤判斷吧。服務器

解決:從ContentType.getCharset()讀取不到Charset時,默認使用UTF-8ide


正確的方法是獲取內容編碼時的格式:函數

- 調用httpResponse.getEntiry()獲取返回結果編碼

- 調用ContentType.get()獲取內容類型spa

- 調用ContentType.getCharset()獲取編碼格式接口

- 調用EntityUtils.toString()將返回結果格式化爲字符串utf-8

public class RespStr implements ResponseHandler<String> {
    @Override
    public String handleResponse(HttpResponse httpResponse) throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        if (entity == null) {
            throw new ClientProtocolException("Response contains no content");
        }

        // 讀取返回內容
        ContentType contentType = ContentType.getOrDefault(entity);
        Charset charset = contentType.getCharset();
        return EntityUtils.toString(entity, charset == null ? Charset.forName("utf-8") : charset);
    }
}字符串

ResponseHandler<T>httpclient包內提供的接口,實現函數handleResponse()處理HTTP返回結果。get

相關文章
相關標籤/搜索