在Android開發中,Android SDK附帶了Apache的HttpClient,它是一個完善的客戶端。它提供了對HTTP協議的全面支持,能夠使用HttpClient的對象來執行HTTP GET和HTTP POST調用。java
HTTP工做原理:android
1.客戶端(通常是指瀏覽器,這裏是指本身寫的程序)與服務器創建鏈接apache
2.創建鏈接後,客戶端向服務器發送請求瀏覽器
3.服務器接收到請求後,向客戶端發送響應信息服務器
4.客戶端與服務器斷開鏈接網絡
HttpClient的通常使用步驟:app
1.使用DefaultHttpClient類實例化HttpClient對象ide
2.建立HttpGet或HttpPost對象,將要請求的URL經過構造方法傳入HttpGet或HttpPost對象。post
3.調用execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。google
4.經過HttpResponse接口的getEntity方法返回響應信息,並進行相應的處理。
最後記得要在AndroidManifest.xml文件添加網絡權限
<uses-permission android:name="android.permission.INTERNET" />
下面是具體的例子:
1.使用HttpClient來執行GET調用
在LogCat窗口就能看到輸出的信息
- package com.lingdududu.http;
- import java.io.InputStream;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- public class HttpGetActivity extends Activity {
- String uri = "http://developer.android.com/";
- final String TAG_STRING = "TAG";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- try {
- //獲得HttpClient對象
- HttpClient getClient = new DefaultHttpClient();
- //獲得HttpGet對象
- HttpGet request = new HttpGet(uri);
- //客戶端使用GET方式執行請教,得到服務器端的迴應response
- HttpResponse response = getClient.execute(request);
- //判斷請求是否成功
- if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
- Log.i(TAG_STRING, "請求服務器端成功");
- //得到輸入流
- InputStream inStrem = response.getEntity().getContent();
- int result = inStrem.read();
- while (result != -1){
- System.out.print((char)result);
- result = inStrem.read();
- }
- //關閉輸入流
- inStrem.close();
- }else {
- Log.i(TAG_STRING, "請求服務器端失敗");
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
使用HTTP GET調用有一個缺點就是,請求的參數做爲URL一部分來傳遞,以這種方式傳遞的時候,URL的長度應該在2048個字符以內。若是超出這個這範圍,就要使用到HTTP POST調用。
2.使用HttpClient來執行POST調用
使用POST調用進行參數傳遞時,須要使用NameValuePair來保存要傳遞的參數。NameValuePair封裝了一個鍵/值組合。另外,還須要設置所使用的字符集。
- package com.androidbook.services.httppost;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import android.app.Activity;
- import android.os.Bundle;
- public class HttpPostActivity extends Activity {
- String uri = "http://developer.android.com/";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- BufferedReader in = null;
- try {
- HttpClient client = new DefaultHttpClient();
- HttpPost request = new HttpPost("http://code.google.com/android/");
- //使用NameValuePair來保存要傳遞的Post參數
- List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
- //添加要傳遞的參數
- postParameters.add(new BasicNameValuePair("id", "12345"));
- postParameters.add(new BasicNameValuePair("username", "dave"));
- //實例化UrlEncodedFormEntity對象
- UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
- postParameters);
- //使用HttpPost對象來設置UrlEncodedFormEntity的Entity
- request.setEntity(formEntity);
- HttpResponse response = client.execute(request);
- in = new BufferedReader(
- new InputStreamReader(
- response.getEntity().getContent()));
- StringBuffer string = new StringBuffer("");
- String lineStr = "";
- while ((lineStr = in.readLine()) != null) {
- string.append(lineStr + "\n");
- }
- in.close();
- String resultStr = string.toString();
- System.out.println(resultStr);
- } catch(Exception e) {
- // Do something about exceptions
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }