[HttpClient]HTTPClient PostMethod 中文乱码问题解决方案(2种)


HTTPClient PostMethod 中文乱码问题解决方案(2种)

 

Apache HttpClient ( http://jakarta.apache.org/commons/httpclient/ ) 是一个纯 Java 的HTTP 协议的客户端编程工具包, 对 HTTP 协议的支持相当全面, 更多细节也可以参考IBM 网站上的这篇文章 HttpClient入门 (http://www.ibm.com/developerworks/cn/opensource/os-httpclient/ ).

 

不过在实际使用中, 还是发现按照最基本的方式调用 HttpClient 时, 并不支持 UTF-8 编码。

 

现在给出2个解决方案:

 

一、在调用PostMethod方法时设置字符编码:

[java]   view plain  copy
 print ?
  1. PostMethod postMethod = new PostMethod(  
  2.         "http://127.0.0.1:8080/HttpClientServer/login.do");  
  3. postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");  

 

 

二、重载PostMethod的getRequestCharSet()方法, 返回我们需要的编码(字符集)名称, 就可以解决 UTF-8 或者其它非默认编码提交 POST 请求时的乱码问题了.

 

[java]   view plain  copy
 print ?
  1. //Inner class for UTF-8 support     
  2.    public static class UTF8PostMethod extends PostMethod{     
  3.        public UTF8PostMethod(String url){     
  4.            super(url);     
  5.        }     
  6.        @Override    
  7.        public String getRequestCharSet() {     
  8.            //return super.getRequestCharSet();     
  9.            return "utf-8";     
  10.        }     
  11.    }       

[java]   view plain  copy
 print ?
  1. PostMethod postMethod = new UTF8PostMethod(  
  2.                 "http://127.0.0.1:8080/HttpClientServer/login.do");  

 

三、最后服务器端要配合客户端,设置下编码字符集:

[java]   view plain  copy
 print ?
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.     //解决中文乱码问题,此步不可少  
  4.     request.setCharacterEncoding("UTF-8");  
  5.     response.setContentType("text/html");  
  6.     response.setCharacterEncoding("UTF-8");  
  7.     PrintWriter out = response.getWriter();  
  8.     String username = (String) request.getParameter("username");  
  9.     String password = (String) request.getParameter("password");  
  10.     System.out.println("******************** doPost被执行了 ********************");  
  11.     System.out.println("您的请求参数为:/tusername:" + username + "/tpassword:"  
  12.             + password);  
  13.     out.print("您的请求参数为:/tusername:" + username + "/tpassword:" + password);  
  14.     out.flush();  
  15.     out.close();  
  16. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值