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

HttpURLConnection 與 HttpClient:用法、差異與回呼式封裝

編輯:關於 Android 程式設計

多數 App 都要跟伺服器要資料。Android 上能用的協定不少,但 HTTP 無疑是最普遍的一種。本文不談協定本身,只聚焦兩組 API: traditional 的 HttpClient 與官方長期推薦的 HttpURLConnection,最後示範如何把它封裝成類似 jQuery.ajax 的簡潔寫法。

出發之前,先在 AndroidManifest.xml 加上網路權限:

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

一、HttpURLConnection

GET 請求

網路 I/O 屬於耗時操作,不可在主執行緒執行,否則會觸發 NetworkOnMainThreadException,因此一律開新執行緒。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

private void connectWithHttpURLConnection() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection connection = null;
            try {
                // 由 URL 取得連線物件
                URL url = new URL("https://www.jb51.net");
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                // 連線與讀取逾時,單位毫秒
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);

                InputStream in = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                // 此處省略資料處理;若要更新 UI,需切回主執行緒
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }).start();
}

POST 請求

import java.io.DataOutputStream;

connection.setRequestMethod("POST");
DataOutputStream data = new DataOutputStream(connection.getOutputStream());
data.writeBytes("stu_no=12345&stu_name=Tom");

多個參數以 & 分隔。若結構較複雜,建議改用 JSON 序列化後送出,並記得設定 Content-Type 與 Content-Length 標頭。

二、HttpClient

GET 請求

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://www.jb51.net");
HttpResponse httpResponse = httpClient.execute(httpGet);

// 由狀態碼判斷結果,200 成功、404 找不到
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity);
    // 中文情境請指定編碼:EntityUtils.toString(entity, "utf-8");
}

POST 請求

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://www.jb51.net");

// 以 NameValuePair 承載參數
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("stu_no", "12345"));
data.add(new BasicNameValuePair("stu_name", "Tom"));

httpPost.setEntity(new UrlEncodedFormEntity(data, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
// 後續處理與 GET 相同

重要提醒:Android 6.0 已移除 HttpClient

從 API 23 起,Apache HttpClient 相關類別已從 SDK 中移除,新的 compileSdk 会直接編譯失敗。若維護舊專案必須沿用,需在 build.gradle 中手動加入 useLibrary 'org.apache.http.legacy';新專案請直接採用 HttpURLConnection 或 OkHttp。

三、封裝成回呼式 API

寫過 jQuery 的人應該都記得這種簡潔:

$.post("https://www.jb51.net", {
    "stu_no": 12345,
    "stu_name": "Tom",
}).done(function () {
    // 成功
}).fail(function () {
    // 失敗
}).always(function () {
    // 無論結果
});

要在 Android 上達到類似效果,關鍵是回呼介面。

步驟一:定義回呼介面

public interface HttpCallbackListener {
    void onFinish(String response);
    void onError(Exception e);
}

步驟二:把請求邏輯抽成靜態方法

方法設為 static 可省去每次呼叫都要 new 的麻煩;內部開新執行緒處理網路,完成後透過 listener 回呼,主執行緒就能收到結果。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTool {
    public static void sendRequest(final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

步驟三:呼叫

String url = "https://www.jb51.net";
HttpTool.sendRequest(url, new HttpCallbackListener() {
    @Override
    public void onFinish(String response) {
        // 處理回傳結果
    }

    @Override
    public void onError(Exception e) {
        // 處理失敗
    }
});

步驟四:加上 POST 支援

在 GET 版本上多收一個 params 參數,寫入輸出串流即可:

public static void sendRequest(final String address, final String params,
                               final HttpCallbackListener listener) {
    // 與 GET 版本共用大部分邏輯,差別在 setRequestMethod("POST")
    // 並以 DataOutputStream 寫入 params
}

不過要提醒的是,回呼目前是在子執行緒觸發,直接更新 UI 仍會出錯,需在 onFinish 中透過 runOnUiThread 或 Handler 切回主執行緒。另外這份封裝並未處理 HTTPS、 gzip 解壓縮、重導轉與連線集區,正式專案建議改用 OkHttp 或 Retrofit,它們在連線重用、攔截器與非同步排程上都成熟得多。

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