apache fluent 乱码

来源:互联网 发布:环球天下期货软件 编辑:程序博客网 时间:2024/06/06 01:50

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。

不幸的是只能使用客户化的response handler重写默认字符集。

注:使用addHeader("Content-Type","text/html;charset=utf-8")无法解决上面的问题

Request.Get(url)//获取数据
    .execute()
    .handleResponse(
        //防止中文乱码
        new ResponseHandler<String>() {
            @Override
            public 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 and not 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();

0 0
原创粉丝点击