Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡編程:HttpURLConnection 與 HttpClient 實戰對比

編輯:關於 Android 程式設計

上一篇講了 URLConnection,它能很方便地與指定站點交換信息。它還有一個專為 HTTP 場景增強的子類——HttpURLConnection,在基礎上補充了一批操作 HTTP 資源的便捷方法。

一、HttpURLConnection 的增量能力

setRequestMethod(String)   // 設置請求方法
getResponseCode()          // 獲取服務器響應碼
getResponseMessage()       // 獲取響應消息

GET 請求:

conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);   // 連接超時
conn.setReadTimeout(8000);      // 讀取超時

POST 請求:

conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

釋放連接:

if (conn != null) conn.disconnect();

二、標準六步流程

// ① 把地址封裝成 URL 對象
URL url = new URL(String spec);

// ② 獲取連接對象(此時尚未真正連接)
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// ③ 初始化連接參數
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);

// ④ 建立連接
conn.connect();

// ⑤ 獲取響應流
InputStream is = conn.getInputStream();

// ⑥ 按需處理流中的數據(字符串、圖片等)

三、實戰:下載圖片並做本地緩存

這個例子加了一個小技巧:首次加載網絡圖片時順手寫入本地緩存,之後直接從緩存讀取,省掉重複的網絡請求。

布局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="加載圖片" />

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

核心邏輯:

public class MainActivity extends Activity {
    private ImageView iv;
    private String path = "https://example.com/logo.png";
    public static final int SUCCESS = 0x1;
    public static final int FAIL = 0x0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    iv.setImageBitmap((Bitmap) msg.obj);
                    break;
                case FAIL:
                    Toast.makeText(MainActivity.this, "請求失敗",
                            Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    public void onClick(View view) {
        final File cacheFile = new File(getCacheDir(), "a2.jpg");
        if (cacheFile.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(
                    cacheFile.getAbsolutePath());
            iv.setImageBitmap(bitmap);
        } else {
            new Thread() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn =
                                (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.connect();

                        if (conn.getResponseCode() == 200) {
                            InputStream is = conn.getInputStream();
                            // 寫入本地緩存
                            FileOutputStream fos =
                                    new FileOutputStream(cacheFile);
                            byte[] b = new byte[1024];
                            int len;
                            while ((len = is.read(b)) != -1) {
                                fos.write(b, 0, len);
                            }
                            fos.flush();
                            fos.close();

                            Bitmap bitmap = BitmapFactory.decodeFile(
                                    cacheFile.getAbsolutePath());
                            Message msg = Message.obtain();
                            msg.what = SUCCESS;
                            msg.obj = bitmap;
                            mHandler.sendMessage(msg);
                        } else {
                            Message msg = Message.obtain();
                            msg.what = FAIL;
                            mHandler.sendMessage(msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }
}

注意幾個細節:網絡請求在子線程執行;結果通過 Handler 回到主線程更新 UI;getCacheDir() 是應用私有緩存目錄,系統在空間緊張時可以清理,適合放這類可重新下載的數據。

四、HttpClient:另一種選擇

Android 5.0 之前 HttpClient 是主流選擇,5.0 之後被 HttpURLConnection 取代,6.0 中則被完全移除。它由 Apache 提供,功能與 HttpURLConnection 幾乎重合,但用法差異很大。

為什麼曾經流行?如果只是向一個簡單頁面發請求並讀響應,HttpURLConnection 綽綽有餘。但真實的 Web 站點往往沒這麼簡單:需要登錄、需要權限、需要維持會話狀態。這時就要處理 Session 和 Cookie,而 HttpClient 在這方面提供了更完善的支持。

它與瀏覽器的區別: HttpClient 只是一個 HTTP 客戶端,不是瀏覽器。它能發請求、收響應,但不會緩存響應、不執行頁面中嵌入的 JavaScript、也不解析 HTML。它會自動維護與服務器之間的 Session 狀態,前提是使用同一個 HttpClient 對象發送多次請求。

使用步驟

// a) 創建 HttpClient
HttpClient client = new DefaultHttpClient();

// b) 根據需要創建 Get 或 Post 對象
HttpGet get = new HttpGet(url);
HttpPost post = new HttpPost(url);

// c) 添加請求參數
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pwd", pwd));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

// d) 發送請求
HttpResponse response = client.execute(post);

// e) 解析響應
int code = response.getStatusLine().getStatusCode();  // 200 表示成功
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");

五、不同響應類型的解析

HttpClient 可以返回多種格式的數據,需要區分處理:

  • 普通文本:直接用 EntityUtils.toString() 轉字符串;
  • HTML:同樣按字符串處理,再按需提取;
  • XML:可選 SAX、DOM、DOM4J 或 PULL 解析;
  • JSON:按對象/數組結構逐層解析。

六、兩個反覆會遇到的問題

中文亂碼

三種常見處理方式:

// 1. 對參數編碼
String n = URLEncoder.encode("張三", "UTF-8");

// 2. 從字節數組還原(該方式已過時)
String n = EncodingUtils.getString("張三".getBytes(), "UTF-8");

// 3. 顯式指定請求頭字符集
conn.setRequestProperty("Charset", "UTF-8");

版本兼容

HttpClient 在 5.1 時已被標記為過時,官方不再推薦;6.0 中直接被移除。如果維護老項目必須使用,需要把編譯配置調整到相應版本,或者直接引入 Apache 官方提供的獨立 httpclient 依賴。新項目請直接使用 HttpURLConnection 或 OkHttp 等現代方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved