zoukankan      html  css  js  c++  java
  • HttpClient使用Post和Get提交参数

    1. package httpclient;  
    2.   
    3. import java.io.IOException;  
    4. import java.net.URLEncoder;  
    5.   
    6. import org.apache.commons.httpclient.HttpClient;  
    7. import org.apache.commons.httpclient.HttpMethod;  
    8. import org.apache.commons.httpclient.NameValuePair;  
    9. import org.apache.commons.httpclient.methods.GetMethod;  
    10. import org.apache.commons.httpclient.methods.PostMethod;  
    11.   
    12. public class HttpClientTest {  
    13.   
    14.     public static void main(String[] args) throws Exception{  
    15.         String url = "/webservices/DomesticAirline.asmx/getDomesticAirlinesTime";  
    16.         String host = "www.webxml.com.cn";  
    17.         String param = "startCity="+URLEncoder.encode("杭州", "utf-8")+"&lastCity=&theDate=&userID=";  
    18.         HttpClient httpClient = new HttpClient();  
    19.         httpClient.getHostConfiguration().setHost(host, 80, "http");          
    20.           
    21.         HttpMethod method = getMethod(url, param);  
    22.         //HttpMethod method = postMethod(url);  
    23.           
    24.         httpClient.executeMethod(method);  
    25.           
    26.         String response = method.getResponseBodyAsString();  
    27.         //String response = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));                  
    28.         System.out.println(response);  
    29.     }  
    30.       
    31.     private static HttpMethod getMethod(String url,String param) throws IOException{  
    32.         GetMethod get = new GetMethod(url+"?"+param);  
    33.         get.releaseConnection();  
    34.         return get;  
    35.     }  
    36.           
    37.     private static HttpMethod postMethod(String url) throws IOException{   
    38.         PostMethod post = new PostMethod(url);  
    39.         post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");    
    40.         NameValuePair[] param = { new NameValuePair("startCity","杭州"),  
    41.                 new NameValuePair("lastCity","沈阳"),  
    42.                 new NameValuePair("userID",""),  
    43.                 new NameValuePair("theDate","") } ;  
    44.         post.setRequestBody(param);  
    45.         post.releaseConnection();  
    46.         return post;  
    47.     }  
    48. }  

       

    戒骄戒躁,一步一个脚印
  • 相关阅读:
    Linux系统中/和是什么意思,和window系统有什么区别?
    给自己的U盘设定图标
    我的第一篇文章
    大端小端
    好玩的地图
    英语流利说 第28天
    英语流利说 第27天
    英语流利说 第26天
    英语流利说 第25天
    英语流利说 第24天
  • 原文地址:https://www.cnblogs.com/sophelia-M/p/4094393.html
Copyright © 2011-2022 走看看