接入百度AI语音识别云服务时踩到的一个坑,ContentType读取不到Charset

原因:不是所有Web服务器都正确返回了内容编码格式,那就再增加一个错误判断吧。

解决:从ContentType.getCharset()读取不到Charset时,默认使用UTF-8


正确的方法是获取内容编码时的格式:

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

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

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

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

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返回结果。

猜你喜欢

转载自blog.51cto.com/13851865/2473642
今日推荐