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

如果PostMethod提交的是中文字符,需要加上相应的编码格式:
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk"); 

如果GetMethod提交的参数有中文字符,需要先转换成utf-8格式:
URLEncoder.encode("杭州", "utf-8");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值