apache fluent 乱码

本文介绍如何解决Apache HttpClient在处理未明确指定编码的网页内容时出现的乱码问题,通过自定义响应处理器实现对UTF-8编码的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值