HttpClient通过HttpPost传递参数

HttpClient新版本(新老版本没有做明确界定,Sorry!) 
Java代码   收藏代码
  1. package http;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import org.apache.http.NameValuePair;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  9. import org.apache.http.client.methods.HttpPost;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11. import org.apache.http.message.BasicNameValuePair;  
  12.   
  13. public class HttpTests {  
  14.   
  15.     /** 
  16.      * @param args 
  17.      * @throws Exception 
  18.      */  
  19.     public static void main(String[] args) throws Exception {  
  20.         HttpClient httpclient = new DefaultHttpClient();  
  21.         HttpPost httpPost = new HttpPost("******/abc");  
  22.         List nvps = new ArrayList();  
  23.         nvps.add(new BasicNameValuePair("username""vip"));  
  24.         nvps.add(new BasicNameValuePair("password""secret"));  
  25.         httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
  26.         httpclient.execute(httpPost);  
  27.         httpclient.getConnectionManager().shutdown();  
  28.     }  
  29.   
  30. }  

HttpClient 老版本: 
Java代码   收藏代码
  1. package http;  
  2.   
  3. import org.apache.commons.httpclient.HttpClient;  
  4. import org.apache.commons.httpclient.NameValuePair;  
  5. import org.apache.commons.httpclient.methods.PostMethod;  
  6.   
  7. public class HttpTests {  
  8.   
  9.     /** 
  10.      * @param args 
  11.      * @throws Exception 
  12.      */  
  13.     public static void main(String[] args) throws Exception {  
  14.         HttpClient httpclient = new HttpClient();  
  15.         PostMethod httpPost =new PostMethod("******/abc");  
  16.         NameValuePair[] param = { new NameValuePair("username""vip")};  
  17.         httpPost.setRequestBody(param);   
  18.         httpclient.executeMethod(httpPost);  
  19.     }  
  20.   
  21. }  

你可能感兴趣的:(网络编程,httpclient)