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

    在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.  
  3. import java.io.InputStream;  
  4.  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.HttpStatus;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10.  
  11. import android.app.Activity;  
  12. import android.os.Bundle;  
  13. import android.util.Log;  
  14.  
  15. public class HttpGetActivity extends Activity {  
  16.     String uri = "http://developer.android.com/";  
  17.     final String TAG_STRING = "TAG";  
  18.     @Override 
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.           
  23.         try {  
  24.             //得到HttpClient對象  
  25.             HttpClient getClient = new DefaultHttpClient();  
  26.             //得到HttpGet對象  
  27.             HttpGet request = new HttpGet(uri);  
  28.             //客戶端使用GET方式執行請教,獲得服務器端的迴應response  
  29.             HttpResponse response = getClient.execute(request);  
  30.             //判斷請求是否成功    
  31.             if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  32.                 Log.i(TAG_STRING, "請求服務器端成功");  
  33.                 //獲得輸入流  
  34.                 InputStream  inStrem = response.getEntity().getContent();  
  35.                 int result = inStrem.read();  
  36.                 while (result != -1){  
  37.                     System.out.print((char)result);  
  38.                     result = inStrem.read();  
  39.                 }  
  40.                 //關閉輸入流  
  41.                 inStrem.close();      
  42.             }else {  
  43.                 Log.i(TAG_STRING, "請求服務器端失敗");  
  44.             }             
  45.         } catch (Exception e) {  
  46.             // TODO Auto-generated catch block  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  

使用HTTP GET調用有一個缺點就是,請求的參數作爲URL一部分來傳遞,以這種方式傳遞的時候,URL的長度應該在2048個字符之內。如果超出這個這範圍,就要使用到HTTP POST調用。

2.使用HttpClient來執行POST調用

 使用POST調用進行參數傳遞時,需要使用NameValuePair來保存要傳遞的參數。NameValuePair封裝了一個鍵/值組合。另外,還需要設置所使用的字符集。

  1. package com.androidbook.services.httppost;  
  2.  
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.  
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.HttpClient;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16.  
  17. import android.app.Activity;  
  18. import android.os.Bundle;  
  19.  
  20. public class HttpPostActivity extends Activity {  
  21.     String uri = "http://developer.android.com/";  
  22.     @Override 
  23.     public void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.main);  
  26.  
  27.         BufferedReader in = null;  
  28.         try {  
  29.             HttpClient client = new DefaultHttpClient();  
  30.             HttpPost request = new HttpPost("http://code.google.com/android/");  
  31.             //使用NameValuePair來保存要傳遞的Post參數  
  32.             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
  33.             //添加要傳遞的參數    
  34.             postParameters.add(new BasicNameValuePair("id""12345"));  
  35.             postParameters.add(new BasicNameValuePair("username""dave"));  
  36.             //實例化UrlEncodedFormEntity對象  
  37.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  38.                     postParameters);  
  39.  
  40.             //使用HttpPost對象來設置UrlEncodedFormEntity的Entity  
  41.             request.setEntity(formEntity);  
  42.             HttpResponse response = client.execute(request);  
  43.             in = new BufferedReader(  
  44.                     new InputStreamReader(  
  45.                             response.getEntity().getContent()));  
  46.  
  47.             StringBuffer string = new StringBuffer("");  
  48.             String lineStr = "";  
  49.             while ((lineStr = in.readLine()) != null) {  
  50.                 string.append(lineStr + "\n");  
  51.             }  
  52.             in.close();  
  53.  
  54.             String resultStr = string.toString();  
  55.             System.out.println(resultStr);  
  56.         } catch(Exception e) {  
  57.             // Do something about exceptions  
  58.         } finally {  
  59.             if (in != null) {  
  60.                 try {  
  61.                     in.close();  
  62.                 } catch (IOException e) {  
  63.                     e.printStackTrace();  
  64.                 }  
  65.             }  
  66.         }  
  67.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章