TShopping

 找回密碼
 註冊
搜索
查看: 1325|回復: 0
打印 上一主題 下一主題

[教學] 【Android進階學習】Http編程之HttpClient

[複製鏈接]
跳轉到指定樓層
1#
發表於 2016-2-18 23:55:52 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
    在Android開發中,Android SDK附帶了Apache的HttpClient,它是一個完善的客戶端。它提供了對HTTP協議的全面支持,可以使用HttpClient的對象來執行HTTP GET和HTTP POST調用。
HTTP工作原理:
1.客戶端(一般是指瀏覽器,這裡是指自己寫的程序)與服務器建立連接
2.建立連接後,客戶端向服務器發送請求
3.服務器接收到請求後,向客戶端發送響應信息
4.客戶端與服務器斷開連接
HttpClient的一般使用步驟:
1.使用DefaultHttpClient類實例化HttpClient對象
2.創建HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。
3.調用execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。
4.通過HttpResponse接口的getEntity方法返迴響應信息,並進行相應的處理。
最後記得要在AndroidManifest.xml文件添加網絡權限
<uses-permission android:name="android.permission.INTERNET" />
下面是具體的例子:
1.使用HttpClient來執行GET調用
在LogCat窗口就能看到輸出的信息
  1. package com.lingdududu.http;  

  2. import java.io.InputStream;  

  3. import org.apache.http.HttpResponse;  
  4. import org.apache.http.HttpStatus;  
  5. import org.apache.http.client.HttpClient;  
  6. import org.apache.http.client.methods.HttpGet;  
  7. import org.apache.http.impl.client.DefaultHttpClient;  

  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.util.Log;  

  11. public class HttpGetActivity extends Activity {  
  12.     String uri = "http://developer.android.com/";  
  13.     final String TAG_STRING = "TAG";  
  14.     @Override
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.          
  19.         try {  
  20.             //得到HttpClient對象
  21.             HttpClient getClient = new DefaultHttpClient();  
  22.             //得到HttpGet對象  
  23.             HttpGet request = new HttpGet(uri);  
  24.             //客戶端使用GET方式執行請教,獲得服務器端的回應response  
  25.             HttpResponse response = getClient.execute(request);  
  26.             //判斷請求是否成功   
  27.             if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  28.                 Log.i(TAG_STRING, "请求服务器端成功");  
  29.                //獲得輸入流
  30.                 InputStream  inStrem = response.getEntity().getContent();  
  31.                 int result = inStrem.read();  
  32.                 while (result != -1){  
  33.                     System.out.print((char)result);  
  34.                     result = inStrem.read();  
  35.                 }  
  36.                 //關閉輸入流
  37.                 inStrem.close();      
  38.             }else {  
  39.                 Log.i(TAG_STRING, "请求服务器端失败");  
  40.             }            
  41.         } catch (Exception e) {  
  42.             // TODO Auto-generated catch block  
  43.             e.printStackTrace();  
  44.         }  
  45.     }  
  46. }
複製代碼

使用HTTP GET調用有一個缺點就是,請求的參數作為URL一部分來傳遞,以這種方式傳遞的時候,URL的長度應該在2048個字符之內。如果超出這個這範圍,就要使用到HTTP POST調用。
2.使用HttpClient來執行POST調用
使用POST調用進行參數傳遞時,需要使用NameValuePair來保存要傳遞的參數。NameValuePair封裝了一個鍵/值組合。另外,還需要設置所使用的字符集。
  1. package com.androidbook.services.httppost;  

  2. import java.io.BufferedReader;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  

  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.message.BasicNameValuePair;  

  14. import android.app.Activity;  
  15. import android.os.Bundle;  

  16. public class HttpPostActivity extends Activity {  
  17.     String uri = "http://developer.android.com/";  
  18.     @Override
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  

  22.         BufferedReader in = null;  
  23.         try {  
  24.             HttpClient client = new DefaultHttpClient();  
  25.             HttpPost request = new HttpPost("http://code.google.com/android/");  
  26.             //使用NameValuePair來保存要傳遞的Post參數  
  27.             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
  28.             //添加要傳遞的參數  
  29.             postParameters.add(new BasicNameValuePair("id", "12345"));  
  30.             postParameters.add(new BasicNameValuePair("username", "dave"));  
  31.             //實例化UrlEncodedFormEntity對象  
  32.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  33.                     postParameters);  

  34.             //使用HttpPost對象來設置UrlEncodedFormEntity的Entity  
  35.             request.setEntity(formEntity);  
  36.             HttpResponse response = client.execute(request);  
  37.             in = new BufferedReader(  
  38.                     new InputStreamReader(  
  39.                             response.getEntity().getContent()));  

  40.             StringBuffer string = new StringBuffer("");  
  41.             String lineStr = "";  
  42.             while ((lineStr = in.readLine()) != null) {  
  43.                 string.append(lineStr + "\n");  
  44.             }  
  45.             in.close();  

  46.             String resultStr = string.toString();  
  47.             System.out.println(resultStr);  
  48.         } catch(Exception e) {  
  49.             // Do something about exceptions  
  50.         } finally {  
  51.             if (in != null) {  
  52.                 try {  
  53.                     in.close();  
  54.                 } catch (IOException e) {  
  55.                     e.printStackTrace();  
  56.                 }  
  57.             }  
  58.         }  
  59.     }  
  60. }
複製代碼


 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-26 04:24 , Processed in 0.086598 second(s), 22 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表