zoukankan      html  css  js  c++  java
  • Java模拟POST表单提交HttpClient操作

    1. public static void Login() {  
    2.        String url = "http://www.***.com/login";  
    3.        PostMethod postMethod = new PostMethod(url);  
    4.        // 填入各个表单域的值  
    5.        NameValuePair[] data = {  
    6.                new NameValuePair("account", "yijianfeng_vip@163.com"),  
    7.                new NameValuePair("nextUrl", ""),  
    8.                new NameValuePair("lcallback", ""),  
    9.                new NameValuePair("password    ", "******"),  
    10.                new NameValuePair("persistent", "1"), };  
    11.        // 将表单的值放入postMethod中  
    12.        postMethod.setRequestBody(data);  
    13.        // 执行postMethod  
    14.        int statusCode = 0;  
    15.        try {  
    16.            statusCode = httpClient.executeMethod(postMethod);  
    17.        } catch (HttpException e) {  
    18.            e.printStackTrace();  
    19.        } catch (IOException e) {  
    20.            e.printStackTrace();  
    21.        }  
    22.        // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发  
    23.        // 301或者302  
    24.        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY  
    25.                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
    26.            // 从头中取出转向的地址  
    27.            Header locationHeader = postMethod.getResponseHeader("location");  
    28.            String location = null;  
    29.            if (locationHeader != null) {  
    30.                location = locationHeader.getValue();  
    31.                System.out.println("diandianLogin:" + location);  
    32.            } else {  
    33.                System.err.println("Location field value is null.");  
    34.            }  
    35.            return;  
    36.        } else {  
    37.            System.out.println(postMethod.getStatusLine());  
    38.            String str = "";  
    39.            try {  
    40.                str = postMethod.getResponseBodyAsString();  
    41.            } catch (IOException e) {  
    42.                e.printStackTrace();  
    43.            }  
    44.            System.out.println(str);  
    45.        }  
    46.        postMethod.releaseConnection();  
    47.        return;  
    48.    }  
    49.   
    50.   
    51.   
    52.   
    53.   
    54. 其中需要的jar包:  
    55.   
    56. 1、 commons-httpclient.jar  
    57.   
    58. 2、commons-codec.jar  
    59.   
    60. 3、commons-logging.jar 

    今天开发时,遇到利用Java中HttpClient类以POST方式提交数据,目标收到后中文乱码问题。
    请求端代码:

    Java代码  收藏代码
    1. /** 
    2.  * HttpClient提交参数 
    3.  * @author sunyunfang@126.com 
    4.  */  
    5. public static void main(String[] args) throws IOException {  
    6.     HttpClient client = new HttpClient();  
    7.     client.getHostConfiguration().setHost("127.0.0.1", 8081, "http");  
    8.     // 使用POST方式提交数据  
    9.     HttpMethod method = getPostMethod();  
    10.     client.executeMethod(method);  
    11.     // 打印服务器返回的状态  
    12.     System.out.println(method.getStatusLine());  
    13.     // 打印结果页面  
    14.     String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));  
    15.     // 打印返回的信息  
    16.     System.out.println(response);  
    17.     method.releaseConnection();  
    18. }  
    19.   
    20. // 使用POST方式提交数据  
    21. private static HttpMethod getPostMethod() {  
    22.     String url = "/PushServer/notification.do?action=sendOneMsg";  
    23.     NameValuePair message = new NameValuePair("message", "消息内容。");  
    24.     post.setRequestBody(new NameValuePair[]{message});  
    25.     return post;  
    26. }  
    27.   
    28. // 使用GET方式提交数据  
    29. private static HttpMethod getGetMethod() {  
    30.     return new GetMethod("/PushServer/notification.do?action=sendOneMsg&message=abcd");  
    31. }  


    目标端代码:

    Java代码  收藏代码
    1. /** 
    2.  * 供MsgServer远程调用 
    3.  * @param request 
    4.  * @param response 
    5.  * @return 
    6.  * @throws Exception 
    7.  * @author SunYunfang@126.com 
    8.  */  
    9. public ModelAndView sendOneMsg(HttpServletRequest request,  
    10.         HttpServletResponse response) throws Exception {  
    11.     String message = ServletRequestUtils.getStringParameter(request, "message");  
    12. }  


    这段代码执行后,目标能收到信息,但是中文乱码,也没有找到转码的方法。

    经分析,原来使用 NameValuePair 加入的HTTP请求的参数最终都会转化为 RequestEntity 提交到HTTP服务器。接着在PostMethod的父类 EntityEnclosingMethod 中发现,只要重载getRequestCharSet()方法就能设置提交的编码(字符集)。

    修正后:

    Java代码  收藏代码
      1. /** 
      2.  * HttpClient提交参数 
      3.  * @author SunYunfang@126.com 
      4.  */  
      5. public static void main(String[] args) throws IOException {  
      6.     HttpClient client = new HttpClient();  
      7.     client.getHostConfiguration().setHost("127.0.0.1", 8081, "http");  
      8.     // 使用POST方式提交数据  
      9.     HttpMethod method = getPostMethod();  
      10.     client.executeMethod(method);  
      11.     // 打印服务器返回的状态  
      12.     System.out.println(method.getStatusLine());  
      13.     // 打印结果页面  
      14.     String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));  
      15.     // 打印返回的信息  
      16.     System.out.println(response);  
      17.     method.releaseConnection();  
      18. }  
      19.   
      20. // 使用POST方式提交数据  
      21. private HttpMethod getPostMethod() {  
      22.     String url = "/PushServer/notification.do?action=sendOneMsg";  
      23.     PostMethod post = new UTF8PostMethod(url);  
      24.     NameValuePair message = new NameValuePair("message", "消息内容。");  
      25.     post.setRequestBody(new NameValuePair[]{message});  
      26.     return post;  
      27. }  
      28.   
      29. //Inner class for UTF-8 support     
      30. public static class UTF8PostMethod extends PostMethod{     
      31.     public UTF8PostMethod(String url){     
      32.     super(url);     
      33.     }     
      34.     @Override     
      35.     public String getRequestCharSet() {     
      36.         //return super.getRequestCharSet();     
      37.         return "UTF-8";     
      38.     }  
      39. }  
      40.   
      41. // 使用GET方式提交数据  
      42. private static HttpMethod getGetMethod() {  
      43.     return new GetMethod("/PushServer/notification.do?action=sendOneMsg&message=abcd");  
  • 相关阅读:
    VS2008环境下CEGUI 0.7.1及相关工具的编译(转载 + 额外的注意事项)
    Makefile的学习
    Erlang 程序文档(转)
    erlang 二进制数据
    erlang中命令行传参,以及类型等。
    笔记:JAVA的静态变量、静态方法、静态类
    关于手机定位方案设计
    转:eclipse技巧
    DXUT CD3DArcBall类
    关于模型转向自然化思考
  • 原文地址:https://www.cnblogs.com/timssd/p/5159439.html
Copyright © 2011-2022 走看看