Android開發進階(四)–深入Android通過Apache HTTP訪問HTTP資源 – Android移動開發技術文章_手機開發 Android移動開發教學課程

 HttpClient接口
實現類:DefaultHttpClient這也是常用的一個用於實現HttpClient接口的子類,
HttpClietnt中定義的常用抽象方法

方法名稱 描述
public abstract HttpResponse execute (HttpUriRequest request) 通過HttpUriRequest對象執行返回一個HttpResponse對象
public abstract HttpResponse execute (HttpUriRequest request, HttpContext context) 通過HttpUriRequest對象和HttpContext對象執行返回一個HttpResponse對象

 
HttpResponse接口
HttpResponse接口裡定義瞭一系列的set、get方法

方法名稱 描述
public abstract HttpEntity getEntity () 得到一個HttpEntity對象
public abstract StatusLine getStatusLine () 得到一個StatusLine(也就是HTTP協議中的狀態行我們知道HTPP狀態行由三部分組成:HTTP協議版本,服務器發回的響應狀態代碼,狀態碼的文本描述)接口的實例對象
public abstract Locale getLocale () 得到Locale對象
….相應的set方法  

 
StatusLine接口
StatusLine接口的常用方法。也可以通過其實現的子類BasicStatusLine類裡查看

方法名稱 描述
public abstract ProtocolVersion getProtocolVersion () 得到一個ProtolVersion對象它是一個HTTP版本的封裝類,在這個類裡定義瞭一系列的方法我們可以通過它的getProtocol方法取得協議名稱,getMinor得到HTPP協議的版本
public abstract String getReasonPhrase () 狀態碼的文本描述
public abstract int getStatusCode () 得到響應狀態碼

 
 
HttpEntity接口
HttpEntity是一個接口

方法名稱 描述
public abstract InputStream getContent () 得到一個輸入流對象,我們可以用這個流來操作文件(例如保存文件到SD卡)
public abstract Header getContentType () 得到Content-Type信息頭
public abstract Header getContentEncoding () 得到Content-Encoding信息頭

 
我們可以通過EntityUtils類,它是一個final類,一個專門針對於處理HttpEntity的幫助類
常用方法
EntityUtils
EntityUtils類的常用方法

方法名稱 描述
public static String getContentCharSet (HttpEntity entity) 設置HttpEntity對象的ContentCharset
public static byte[] toByteArray (HttpEntity entity) 將HttpClient轉換成一個字節數組
public static String toString (HttpEntity entity, String defaultCharset) 通過指定的編碼方式取得HttpEntity裡字符串內容
public static String toString (HttpEntity entity) 取得HttpEntity裡字符串內容

 
NameValuePair
NameValuePair接口是一個簡單的封閉的鍵值對,隻提供瞭一個getName()和一個getValue方法。主要用到的實現類BasicNameVaulePair
 
HttpGet
HttpGet它實現瞭HttpRequest、HttpUriRequest接口
構造方法

方法名稱 描述
public HttpGet () 無參數構造方法用以實例化對象
public HttpGet (URI uri) 通過URI對象構造HttpGet對象
public HttpGet (String uri) 通過指定的uri字符串地址構造實例化HttpGet對象

 
HttpPost
同樣它也實現瞭HttpRequest、HttpUriRequest接口等一系列接口
構造方法

方法名稱 描述
public HttpPost () 無參數構造方法用以實例化對象
public HttpPost (URI uri) 通過URI對象構造HttpPost對象
public HttpPost (String uri) 通過指定的uri字符串地址構造實例化HttpPost對象

 
 
清楚瞭上面的所有常用API後,下面我們能過Apache HTTP來訪問HTTP資源
三步曲:
1.  創建HttpGet或者HttpPost對象,將要請求的URL對象構造方法傳入HttpGet、HttpPost對象
2.  通過HttpClent接口的實現類DefaultClent.的excute(HttpUriRequest request)而我們已經知道HttpGet和HttpPost類都實現瞭HttpUriRequest接口,所以這裡面,我們可以將第1步創建好的HttpGet或者HttpPost對象傳入進來。來得到HttpResponse對象
3.  通過HttpResponse取到返回的一些信息,再做提取
 
實例圖片:
 

帖上一部分源代碼:

佈局文件:

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
   android:orientation="vertical" android:layout_width="fill_parent" 
 
   android:layout_height="fill_parent"> 
 
   <LinearLayout android:orientation="horizontal" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content"> 
 
      <TextView android:layout_width="wrap_content" 
 
        android:layout_height="wrap_content" android:text="url:" /> 
 
      <EditText android:id="@+id/urlText" android:layout_width="fill_parent" 
 
        android:layout_height="wrap_content" 
 
         android:text="http://10.0.2.2:8080/NetServer/queryServlet?bookId=2" /> 
 
   </LinearLayout> 
 
   <LinearLayout android:orientation="horizontal" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content" 
 
      android:gravity="right"> 
 
      <Button android:id="@+id/getBtn" android:text="GET請求" 
 
        android:layout_width="wrap_content" android:layout_height="wrap_content" /> 
 
      <Button android:id="@+id/postBtn" android:text="POST請求" 
 
        android:layout_width="wrap_content" android:layout_height="wrap_content" /> 
 
   </LinearLayout> 
 
   <TextView android:id="@+id/resultView" android:layout_width="fill_parent" 
 
      android:layout_height="wrap_content" /> 
 
   <LinearLayout android:orientation="horizontal" 
 
      android:layout_width="fill_parent" android:layout_height="wrap_content"> 
 
      <TextView android:layout_width="wrap_content" 
 
        android:layout_height="wrap_content" android:text="圖片url:" /> 
 
  
 
      <EditText android:id="@+id/imageurlText" android:layout_width="fill_parent" 
 
        android:layout_height="wrap_content" android:text="/wp-content/images1/20181005/20111229015137543296.jpg" /> 
 
   </LinearLayout> 
 
   <Button android:id="@+id/imgBtn" android:text="獲取圖片" 
 
      android:layout_width="wrap_content" android:layout_height="wrap_content" 
 
      android:layout_gravity="right" /> 
 
   <ImageView android:id="@+id/imgeView01"  
 
      android:layout_height="wrap_content" android:layout_width="fill_parent" /> 
 
</LinearLayout> 
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

   android:orientation="vertical" android:layout_width="fill_parent"

   android:layout_height="fill_parent">

   <LinearLayout android:orientation="horizontal"

      android:layout_width="fill_parent" android:layout_height="wrap_content">

      <TextView android:layout_width="wrap_content"

        android:layout_height="wrap_content" android:text="url:" />

      <EditText android:id="@+id/urlText" android:layout_width="fill_parent"

        android:layout_height="wrap_content"

         android:text="http://10.0.2.2:8080/NetServer/queryServlet?bookId=2" />

   </LinearLayout>

   <LinearLayout android:orientation="horizontal"

      android:layout_width="fill_parent" android:layout_height="wrap_content"

      android:gravity="right">

      <Button android:id="@+id/getBtn" android:text="GET請求"

        android:layout_width="wrap_content" android:layout_height="wrap_content" />

      <Button android:id="@+id/postBtn" android:text="POST請求"

        android:layout_width="wrap_content" android:layout_height="wrap_content" />

   </LinearLayout>

   <TextView android:id="@+id/resultView" android:layout_width="fill_parent"

      android:layout_height="wrap_content" />

   <LinearLayout android:orientation="horizontal"

      android:layout_width="fill_parent" android:layout_height="wrap_content">

      <TextView android:layout_width="wrap_content"

        android:layout_height="wrap_content" android:text="圖片url:" />

 

      <EditText android:id="@+id/imageurlText" android:layout_width="fill_parent"

        android:layout_height="wrap_content" android:text="/wp-content/images1/20181005/20111229015137543296.jpg" />

   </LinearLayout>

   <Button android:id="@+id/imgBtn" android:text="獲取圖片"

      android:layout_width="wrap_content" android:layout_height="wrap_content"

      android:layout_gravity="right" />

   <ImageView android:id="@+id/imgeView01"

      android:layout_height="wrap_content" android:layout_width="fill_parent" />

</LinearLayout>

 

 

Java代碼:

view plaincopy to clipboardprint?
package com.jiahui.net; 
 
  
 
import java.io.InputStream; 
 
  
 
import org.apache.http.HttpEntity; 
 
import org.apache.http.HttpResponse; 
 
import org.apache.http.StatusLine; 
 
import org.apache.http.client.HttpClient; 
 
import org.apache.http.client.methods.HttpGet; 
 
import org.apache.http.client.methods.HttpPost; 
 
import org.apache.http.impl.client.DefaultHttpClient; 
 
import org.apache.http.util.EntityUtils; 
 
  
 
import android.app.Activity; 
 
import android.graphics.Bitmap; 
 
import android.graphics.BitmapFactory; 
 
import android.os.Bundle; 
 
import android.view.View; 
 
import android.view.View.OnClickListener; 
 
import android.widget.Button; 
 
import android.widget.EditText; 
 
import android.widget.ImageButton; 
 
import android.widget.ImageView; 
 
import android.widget.TextView; 
 
import android.widget.Toast; 
 
  
 
public class HTTPDemoActivity extends Activity { 
 
  
 
       private Button getBtn, postBtn, imageBtn; 
 
       private EditText urlText, imageUrlText; 
 
       private TextView resutlView; 
 
       private ImageView imageView; 
 
  
 
       public void onCreate(Bundle savedInstanceState) { 
 
              super.onCreate(savedInstanceState); 
 
              setContentView(R.layout.main); 
 
  
 
              urlText = (EditText) findViewById(R.id.urlText); 
 
              imageUrlText = (EditText) findViewById(R.id.imageurlText); 
 
  
 
              resutlView = (TextView) findViewById(R.id.resultView); 
 
              getBtn = (Button) findViewById(R.id.getBtn); 
 
              postBtn = (Button) findViewById(R.id.postBtn); 
 
              imageBtn = (Button) findViewById(R.id.imgBtn); 
 
              imageView = (ImageView) findViewById(R.id.imgeView01); 
 
  
 
              getBtn.setOnClickListener(new OnClickListener() { 
 
                     @Override 
 
                     public void onClick(View v) { 
 
                            System.out.println(urlText.getText().toString()); 
 
                            resutlView 
 
                                          .setText(request("GET", urlText.getText().toString())); 
 
                     } 
 
              }); 
 
               
 
              postBtn.setOnClickListener(new OnClickListener() { 
 
                     public void onClick(View v) { 
 
                            System.out.println(urlText.getText().toString()); 
 
                            resutlView 
 
                                          .setText(request("POST", urlText.getText().toString())); 
 
                     } 
 
              }); 
 
              imageBtn.setOnClickListener(new OnClickListener() { 
 
  
 
                     public void onClick(View v) { 
 
  
 
                            getImage(imageUrlText.getText().toString()); 
 
                     } 
 
              }); 
 
       } 
 
       private String request(String method, String url) { 
 
              HttpResponse httpResponse = null; 
 
              StringBuffer result = new StringBuffer(); 
 
              try { 
 
                     if (method.equals("GET")) { 
 
                            // 1.通過url創建HttpGet對象  
 
                            HttpGet httpGet = new HttpGet(url); 
 
                            // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象  
 
                            HttpClient httpClient = new DefaultHttpClient(); 
 
                            httpResponse = httpClient.execute(httpGet); 
 
                            // 3.取得相關信息  
 
                            // 取得HttpEntiy  
 
                            HttpEntity httpEntity = httpResponse.getEntity(); 
 
                            // 得到一些數據  
 
                            // 通過EntityUtils並指定編碼方式取到返回的數據  
 
                            result.append(EntityUtils.toString(httpEntity, "utf-8")); 
 
                            //得到StatusLine接口對象  
 
                            StatusLine statusLine = httpResponse.getStatusLine(); 
 
  
 
                            //得到協議  
 
                            ; 
 
                            result.append("協議:" + statusLine.getProtocolVersion() + "\r\n"); 
 
                            int statusCode = statusLine.getStatusCode(); 
 
  
 
                            result.append("狀態碼:" + statusCode + "\r\n"); 
 
  
 
                     } else if (method.equals("POST")) { 
 
  
 
                            // 1.通過url創建HttpGet對象  
 
                            HttpPost httpPost = new HttpPost(url); 
 
                            // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象  
 
                            HttpClient httpClient = new DefaultHttpClient(); 
 
                            httpResponse = httpClient.execute(httpPost); 
 
                            // 3.取得相關信息  
 
                            // 取得HttpEntiy  
 
                            HttpEntity httpEntity = httpResponse.getEntity(); 
 
                            // 得到一些數據  
 
                            // 通過EntityUtils並指定編碼方式取到返回的數據  
 
                            result.append(EntityUtils.toString(httpEntity, "utf-8")); 
 
                            StatusLine statusLine = httpResponse.getStatusLine(); 
 
                            statusLine.getProtocolVersion(); 
 
                            int statusCode = statusLine.getStatusCode(); 
 
  
 
                            result.append("狀態碼:" + statusCode + "\r\n"); 
 
  
 
                     } 
 
              } catch (Exception e) { 
 
                     Toast.makeText(HTTPDemoActivity.this, "網絡連接異常", Toast.LENGTH_LONG) 
 
                                   .show(); 
 
              } 
 
              return result.toString(); 
 
       } 
 
  
 
       public void getImage(String url) { 
 
              try { 
 
                     // 1.通過url創建HttpGet對象  
 
                     HttpGet httpGet = new HttpGet(url); 
 
                     // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象  
 
                     HttpClient httpClient = new DefaultHttpClient(); 
 
                     HttpResponse httpResponse = httpClient.execute(httpGet); 
 
                     // 3.取得相關信息  
 
                     // 取得HttpEntiy  
 
                     HttpEntity httpEntity = httpResponse.getEntity(); 
 
                     // 4.通過HttpEntiy.getContent得到一個輸入流  
 
                     InputStream inputStream = httpEntity.getContent(); 
 
                     System.out.println(inputStream.available()); 
 
                      
 
                     //通過傳入的流再通過Bitmap工廠創建一個Bitmap  
 
                     Bitmap bitmap = BitmapFactory.decodeStream(inputStream); 
 
                     //設置imageView            
 
                     imageView.setImageBitmap(bitmap); 
 
              } catch (Exception e) { 
 
                     Toast.makeText(HTTPDemoActivity.this, "網絡連接異常", Toast.LENGTH_LONG) 
 
                     .show(); 
 
              } 
 
       } 
 
  
 

package com.jiahui.net;

 

import java.io.InputStream;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.StatusLine;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

 

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageButton;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

 

public class HTTPDemoActivity extends Activity {

 

       private Button getBtn, postBtn, imageBtn;

       private EditText urlText, imageUrlText;

       private TextView resutlView;

       private ImageView imageView;

 

       public void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.main);

 

              urlText = (EditText) findViewById(R.id.urlText);

              imageUrlText = (EditText) findViewById(R.id.imageurlText);

 

              resutlView = (TextView) findViewById(R.id.resultView);

              getBtn = (Button) findViewById(R.id.getBtn);

              postBtn = (Button) findViewById(R.id.postBtn);

              imageBtn = (Button) findViewById(R.id.imgBtn);

              imageView = (ImageView) findViewById(R.id.imgeView01);

 

              getBtn.setOnClickListener(new OnClickListener() {

                     @Override

                     public void onClick(View v) {

                            System.out.println(urlText.getText().toString());

                            resutlView

                                          .setText(request("GET", urlText.getText().toString()));

                     }

              });

             

              postBtn.setOnClickListener(new OnClickListener() {

                     public void onClick(View v) {

                            System.out.println(urlText.getText().toString());

                            resutlView

                                          .setText(request("POST", urlText.getText().toString()));

                     }

              });

              imageBtn.setOnClickListener(new OnClickListener() {

 

                     public void onClick(View v) {

 

                            getImage(imageUrlText.getText().toString());

                     }

              });

       }

       private String request(String method, String url) {

              HttpResponse httpResponse = null;

              StringBuffer result = new StringBuffer();

              try {

                     if (method.equals("GET")) {

                            // 1.通過url創建HttpGet對象

                            HttpGet httpGet = new HttpGet(url);

                            // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象

                            HttpClient httpClient = new DefaultHttpClient();

                            httpResponse = httpClient.execute(httpGet);

                            // 3.取得相關信息

                            // 取得HttpEntiy

                            HttpEntity httpEntity = httpResponse.getEntity();

                            // 得到一些數據

                            // 通過EntityUtils並指定編碼方式取到返回的數據

                            result.append(EntityUtils.toString(httpEntity, "utf-8"));

                            //得到StatusLine接口對象

                            StatusLine statusLine = httpResponse.getStatusLine();

 

                            //得到協議

                            ;

                            result.append("協議:" + statusLine.getProtocolVersion() + "\r\n");

                            int statusCode = statusLine.getStatusCode();

 

                            result.append("狀態碼:" + statusCode + "\r\n");

 

                     } else if (method.equals("POST")) {

 

                            // 1.通過url創建HttpGet對象

                            HttpPost httpPost = new HttpPost(url);

                            // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象

                            HttpClient httpClient = new DefaultHttpClient();

                            httpResponse = httpClient.execute(httpPost);

                            // 3.取得相關信息

                            // 取得HttpEntiy

                            HttpEntity httpEntity = httpResponse.getEntity();

                            // 得到一些數據

                            // 通過EntityUtils並指定編碼方式取到返回的數據

                            result.append(EntityUtils.toString(httpEntity, "utf-8"));

                            StatusLine statusLine = httpResponse.getStatusLine();

                            statusLine.getProtocolVersion();

                            int statusCode = statusLine.getStatusCode();

 

                            result.append("狀態碼:" + statusCode + "\r\n");

 

                     }

              } catch (Exception e) {

                     Toast.makeText(HTTPDemoActivity.this, "網絡連接異常", Toast.LENGTH_LONG)

                                   .show();

              }

              return result.toString();

       }

 

       public void getImage(String url) {

              try {

                     // 1.通過url創建HttpGet對象

                     HttpGet httpGet = new HttpGet(url);

                     // 2.通過DefaultClient的excute方法執行返回一個HttpResponse對象

                     HttpClient httpClient = new DefaultHttpClient();

                     HttpResponse httpResponse = httpClient.execute(httpGet);

                     // 3.取得相關信息

                     // 取得HttpEntiy

                     HttpEntity httpEntity = httpResponse.getEntity();

                     // 4.通過HttpEntiy.getContent得到一個輸入流

                     InputStream inputStream = httpEntity.getContent();

                     System.out.println(inputStream.available());

                    

                     //通過傳入的流再通過Bitmap工廠創建一個Bitmap

                     Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                     //設置imageView         

                     imageView.setImageBitmap(bitmap);

              } catch (Exception e) {

                     Toast.makeText(HTTPDemoActivity.this, "網絡連接異常", Toast.LENGTH_LONG)

                     .show();

              }

       }

 

}

 

 

開發註意事項:

1.要想訪問本地機器不能寫成localhost或者127.0.0.1要寫成10.0.2.2。這是因為Android模擬器(simulator)把它自己作為瞭localhost,也就是說,代碼中使用localhost或者127.0.0.1來訪問,都是訪問模擬器自己!若你想在模擬器simulator上面訪問你的電腦,那麼就使用android內置的IP: 10.0.2.2,10.0.2.2是模擬器設定的特定ip,是你電腦的別名,在模擬器上用10.0.2.2就能成功訪問你的電腦本機。

2.記得加上網絡訪問權限

<uses-permission android:name="android.permission.INTERNET"/>

 源代碼下載:http://up.aiwalls.com/2011/1229/20111229015052893.zip

摘自 jiahui524專欄
 

發佈留言