閱讀764 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android HttpClient基本使用方法

這裏隻介紹如何使用HttpClient發起GET或者POST請求

 

GET 方式

 

Java代碼  收藏代碼
  1. //先將參數放入List,再對參數進行URL編碼  
  2. List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();  
  3. params.add(new BasicNameValuePair("param1""中國"));  
  4. params.add(new BasicNameValuePair("param2""value2"));  
  5.   
  6. //對參數編碼  
  7. String param = URLEncodedUtils.format(params, "UTF-8");  
  8.   
  9. //baseUrl             
  10. String baseUrl = "https://ubs.free4lab.com/php/method.php";  
  11.   
  12. //將URL與參數拚接  
  13. HttpGet getMethod = new HttpGet(baseUrl + "?" + param);  
  14.               
  15. HttpClient httpClient = new DefaultHttpClient();  
  16.   
  17. try {  
  18.     HttpResponse response = httpClient.execute(getMethod); //發起GET請求  
  19.   
  20.     Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼  
  21.     Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取服務器響應內容  
  22. catch (ClientProtocolException e) {  
  23.     // TODO Auto-generated catch block  
  24.     e.printStackTrace();  
  25. catch (IOException e) {  
  26.     // TODO Auto-generated catch block  
  27.     e.printStackTrace();  
  28. }  
 

 

 

POST方式

 

Java代碼  收藏代碼
  1. //和GET方式一樣,先將參數放入List  
  2. params = new LinkedList<BasicNameValuePair>();  
  3. params.add(new BasicNameValuePair("param1""Post方法"));  
  4. params.add(new BasicNameValuePair("param2""第二個參數"));  
  5.               
  6. try {  
  7.     HttpPost postMethod = new HttpPost(baseUrl);  
  8.     postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中  
  9.                   
  10.     HttpResponse response = httpClient.execute(postMethod); //執行POST方法  
  11.     Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼  
  12.     Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容  
  13.                   
  14. catch (UnsupportedEncodingException e) {  
  15.     // TODO Auto-generated catch block  
  16.     e.printStackTrace();  
  17. catch (ClientProtocolException e) {  
  18.     // TODO Auto-generated catch block  
  19.     e.printStackTrace();  
  20. catch (IOException e) {  
  21.     // TODO Auto-generated catch block  
  22.     e.printStackTrace();  
  23. }  

最後更新:2017-04-03 22:31:03

  上一篇:go 簡析Go與其他語言不同的類型
  下一篇:go 8個Python編程語言的變種