zoukankan      html  css  js  c++  java
  • HttpClient 处理中文乱码

    HttpClient 请求的中文乱码问题 
    相关类库: 
    commons-codec-1.3.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar 

    --给请求传递参数

    HttpClient client = new HttpClient();

    HttpMethod method= new PostMethod(url);

    HttpMethodParams params = new HttpMethodParams();

    params.setContentCharset("GB2312");

    method.setParams(params);

     

    方式一:
    最简单的方式,直接输出页面,这里基本上不需要任何设置。

    System.out.println(getMethod.getResponseBodyAsString());

     

    方式二:
    使用流方式读取

    InputStream in = getMethod.getResponseBodyAsStream();

    //这里的编码规则要与上面的相对应

    BufferedReader br = new BufferedReader(new InputStreamReader(in,"GB2312"));

    String tempbf;

    StringBuffer html = new StringBuffer(100);

    while ((tempbf = br.readLine()) != null) {

        html.append(tempbf +" ");

    }

    System.out.println(html.toString());

     

    方式三:
    当然还可以使用这样的方式,因为默认是使用ISO-8859-1,无非就是多进行了几次转码 

    InputStream in = getMethod.getResponseBodyAsStream();

    //这里使用8859-1读取

    BufferedReader br = new BufferedReader(new InputStreamReader(in,"ISO-8859-1"));

    String tempbf;

    StringBuffer html = new StringBuffer(100);

    while ((tempbf = br.readLine()) != null) {

        html.append(tempbf +" ");

    }

    //将8859-1再次转成GB2312

    System.out.println(new String(html.toString().getBytes("ISO-8859-1"),"GB2312"));


    我还是建议使用第一种方法,但我认为本质上是一致的 
    对于请求部分还可以通过如下几种方式进行设置 

    getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"GB2312");

    getMethod.addRequestHeader("Content-Type", "text/html; charset=gb2312");

    转自:http://871421448.iteye.com/blog/1546950

  • 相关阅读:
    【luogu P1040 加分二叉树】 题解
    【luogu P4711 「化学」相对分子质量】 题解
    【luogu P2319 [HNOI2006]超级英雄】 题解
    【luogu P1640 [SCOI2010]连续攻击游戏】 题解
    【luogu P3369 普通平衡树(Treap/SBT)】 模板 Splay
    【luogu P2234 [HNOI2002]营业额统计】 题解
    【luogu P1494 [国家集训队]小Z的袜子】 题解
    【luogu P3901 数列找不同】 题解
    【luogu P3807 卢卡斯定理】 模板
    JAVA IO 体系
  • 原文地址:https://www.cnblogs.com/yixiu868/p/6637645.html
Copyright © 2011-2022 走看看