HttpClient使用Post和Get提交參數

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   sp   java   for   on   

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

HttpClient使用Post和Get提交參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.