原文地址: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窗口就能看到輸出的信息
- 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 getClient = new DefaultHttpClient();
-
- HttpGet request = new HttpGet(uri);
-
- HttpResponse response = getClient.execute(request);
-
- if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
- Log.i(TAG_STRING, "請求服務器端成功");
-
- //第四步: 獲取HttpResponse中的數據
- 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) {
-
- 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對象,代表客戶端
- HttpClient client = new DefaultHttpClient();
-
- //第二步:創建HttpPost請求
- HttpPost request = new HttpPost("http://code.google.com/android/");
-
-
- List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
-
- postParameters.add(new BasicNameValuePair("id", "12345"));
- postParameters.add(new BasicNameValuePair("username", "dave"));
-
- UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
- postParameters);
-
-
- request.setEntity(formEntity);
-
- //第四步:執行請求,獲得HttpServer的響應
- HttpResponse response = client.execute(request);
//第五步:獲取HttpResponse中的數據
- 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) {
-
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }