Android HttpClient用法

原文地址:http://liangruijun.blog.51cto.com/3061169/803097


在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對象,代表一個Http客戶端 
  25.             HttpClient getClient = new DefaultHttpClient();  
  26.             
  27. //第二步:得到HttpGet對象,代表請求的具體內容
  28.             HttpGet request = new HttpGet(uri);  
  1.             //第三步:執行請求。使用HttpClient的execute方法,執行剛纔構建的請求  
  2.             HttpResponse response = getClient.execute(request);  
  3.             //判斷請求是否成功    
  4.             if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  5.                 Log.i(TAG_STRING, "請求服務器端成功");  
  6.                 //獲得輸入流 
  7. //第四步: 獲取HttpResponse中的數據
  8.                 InputStream  inStrem = response.getEntity().getContent();  
  9.                 int result = inStrem.read();  
  10.                 while (result != -1){  
  11.                     System.out.print((char)result);  
  12.                     result = inStrem.read();  
  13.                 }  
  14.                 //關閉輸入流  
  15.                 inStrem.close();      
  16.             }else {  
  17.                 Log.i(TAG_STRING, "請求服務器端失敗");  
  18.             }             
  19.         } catch (Exception e) {  
  20.             // TODO Auto-generated catch block  
  21.             e.printStackTrace();  
  22.         }  
  23.     }  

使用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對象,代表客戶端
  30.             HttpClient client = new DefaultHttpClient();
  31. //第二步:創建HttpPost請求  
  32.             HttpPost request = new HttpPost("http://code.google.com/android/");  
  33.             
  34. //第三步:創建HttpPost請求體,使用NameValuePair來保存要傳遞的Post參數  
  35.             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
  36.             //添加要傳遞的參數    
  37.             postParameters.add(new BasicNameValuePair("id""12345"));  
  38.             postParameters.add(new BasicNameValuePair("username""dave"));  
  39.             //實例化UrlEncodedFormEntity對象  
  40.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  41.                     postParameters);  
  42.  
  43.             //使用HttpPost對象來設置UrlEncodedFormEntity的Entity  
  44.             request.setEntity(formEntity);
  45. //第四步:執行請求,獲得HttpServer的響應
  46.             HttpResponse response = client.execute(request);  
//第五步:獲取HttpResponse中的數據
  1.             in = new BufferedReader(  
  2.                     new InputStreamReader(  
  3.                             response.getEntity().getContent()));  
  4.  
  5.             StringBuffer string = new StringBuffer("");  
  6.             String lineStr = "";  
  7.             while ((lineStr = in.readLine()) != null) {  
  8.                 string.append(lineStr + "\n");  
  9.             }  
  10.             in.close();  
  11.  
  12.             String resultStr = string.toString();  
  13.             System.out.println(resultStr);  
  14.         } catch(Exception e) {  
  15.             // Do something about exceptions  
  16.         } finally {  
  17.             if (in != null) {  
  18.                 try {  
  19.                     in.close();  
  20.                 } catch (IOException e) {  
  21.                     e.printStackTrace();  
  22.                 }  
  23.             }  
  24.         }  
  25.     }  

 

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