httpclient 中文乱码

本文介绍了解决HTTP请求中中文乱码的方法,通过在三个关键位置设置合适的字符编码(如ISO-8859-1转UTF-8),确保了从服务器获取的数据能正确显示中文内容。

 3个地方设置编码,解决乱码问题

 

    public static String GetResponse(HttpMethodBase Method) throws IOException {
        String charset= Method.getResponseCharSet();
        System.out.println("返回的字符编码为:"+charset);
        InputStream responseBody = Method.getResponseBodyAsStream();
//        BufferedReader br = new BufferedReader(new InputStreamReader(responseBody));
        BufferedReader br = new BufferedReader(new InputStreamReader(Method.getResponseBodyAsStream(), "ISO-8859-1"));//1
        String tempbf;
        StringBuffer htmlbf = new StringBuffer(100);
        while ((tempbf = br.readLine()) != null) {
//            htmlbf.append(tempbf);
            htmlbf.append(new String(tempbf.getBytes("iso-8859-1"),"utf-8"));//2
            htmlbf.append("/n");
        }
        return htmlbf.toString();
    }//end GetResponse

 

 

然后在构建GetMethod或PostMethod时也指定编码

          Method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//3

或者        NameValuePair p2 = new NameValuePair( "Content-Type","text/html; charset=utf-8");

post.setRequestBody( new NameValuePair[]{p2})//3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值