您的位置:首页 > 运维架构 > Apache

apache fluent 乱码

2016-05-06 15:12 1831 查看
http://stackoverflow.com/questions/17990684/how-to-use-the-fluent-api-of-apache-httpclient-to-read-utf-8-coded-website服务器返回的信息没有明确指定内容的编码集,因此HttpClient强制使用ISO-8859-1对内容进行编码,而不是UTF-8。不幸的是只能使用客户化的responsehandler重写默认字符集。注:使用addHeader("Content-Type","text/html;charset=utf-8")无法解决上面的问题Request.Get(url)//获取数据.execute().handleResponse(//防止中文乱码new ResponseHandler<String>() {@Overridepublic String handleResponse(final HttpResponse response) throws IOException {return EntityUtils.toString(response.getEntity(), Consts.UTF_8);}});----------------------原文--------------------The response message returned by the server for this URI does not explicitly specify the charset of the content. In such cases HttpClient is forced to use the default charset encoding for HTTP content, which is
ISO-8859-1
andnot
UTF-8
.Unfortunately the only way to override the default content charset used by fluent API is by using a custom response handler
ResponseHandler<String> myHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws IOException {
return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
};

String html = Request.Get("https://kokos.pl/").execute().handleResponse(myHandler);

System.out.println(html);
在使用post发送中文时,服务器接受的是乱码,可通过http://www.cnblogs.com/tecfans/p/3577277.html来解决
List<NameValuePair> forms = Form.form().add("account",this.getJsonString(account)).build();String ret = Request.Post(requestUrl).bodyForm(forms, Charset.forName("utf-8")).execute().returnContent().asString();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: