码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient使用Post和Get提交参数

时间:2014-11-13 12:21:08      阅读:153      评论:0      收藏:0      [点我收藏+]

标签: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提交参数

标签:http   io   ar   os   使用   sp   java   for   on   

原文地址:http://www.cnblogs.com/sophelia-M/p/4094393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!