分享

httpclient 中文乱码

 moonboat 2011-10-11
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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多