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. }  

     

戒骄戒躁,一步一个脚印
原文地址:https://www.cnblogs.com/sophelia-M/p/4094393.html