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

Android 網路請求:HttpURLConnection 與 HttpClient 對比

編輯:關於 Android 程式設計

HTTP 協定可能是目前網際網路上使用最廣泛、最重要的協定,越來越多 Java 應用需要直接透過 HTTP 存取網路資源。Android 提供了兩套工具:JDK 標準的 HttpURLConnection,以及 SDK 內建的 Apache HttpClient。

一、兩者的定位

HttpURLConnection 是 Java 標準類,屬於 java.net 套件。它提供基本的 HTTP 存取能力,但封裝層次低,用起來比較原始。

HttpClient 是 Apache 的開源專案,Android SDK 內建了這個模組。它支援當時最新的 HTTP 協定規格與建議,把請求標頭、參數、實體內容、回應都做了完整封裝,能快速開發出功能完整的 HTTP 程式。

二、能力對照

  • 支援的請求方法:URLConnection 只有 GET 與 POST;HttpClient 有 HEAD、GET、POST、PUT、DELETE、TRACE、OPTIONS,還能自訂任意方法。
  • 標頭處理:URLConnection 對標頭的設定與讀取有諸多限制;HttpClient 可任意送收標頭。
  • 自動重導:兩者都支援,但 HttpClient 是依 HTTP/1.1 規格實作。
  • 持久連線:URLConnection 在 JDK 中無支援;HttpClient 支援 HTTP/1.0 Keep-Alive 與 HTTP/1.1 持久連線。
  • 管線化請求:URLConnection 不支援;HttpClient 支援。
  • 認證機制:URLConnection 僅支援 Basic 認證;HttpClient 支援 Basic 且可自行擴充其他機制。
  • 原始碼:URLConnection 不公開;HttpClient 完全開源。

結論很清楚:功能豐富度與靈活度上,HttpClient 明顯勝出,特別是需要自訂請求方法或高級控制時。

三、HttpURLConnection 範例

String urlAddress = "https://192.168.1.102:8080/AndroidServer/login.do";
URL url;
HttpURLConnection uRLConnection;

// 送出 GET 請求
public String doGet(String username, String password) {
    String getUrl = urlAddress + "?username=" + username + "&password=" + password;
    try {
        url = new URL(getUrl);
        uRLConnection = (HttpURLConnection) url.openConnection();
        InputStream is = uRLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String response = "";
        String readLine = null;
        while ((readLine = br.readLine()) != null) {
            response = response + readLine;
        }
        is.close();
        br.close();
        uRLConnection.disconnect();
        return response;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

// 送出 POST 請求
public String doPost(String username, String password) {
    try {
        url = new URL(urlAddress);
        uRLConnection = (HttpURLConnection) url.openConnection();
        uRLConnection.setDoInput(true);
        uRLConnection.setDoOutput(true);
        uRLConnection.setRequestMethod("POST");
        uRLConnection.setUseCaches(false);
        uRLConnection.setInstanceFollowRedirects(false);
        uRLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        uRLConnection.connect();

        DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
        String content = "username=" + username + "&password=" + password;
        out.writeBytes(content);
        out.flush();
        out.close();

        InputStream is = uRLConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String response = "";
        String readLine = null;
        while ((readLine = br.readLine()) != null) {
            response = response + readLine;
        }
        is.close();
        br.close();
        uRLConnection.disconnect();
        return response;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

四、HttpClient 範例

String urlAddress = "https://192.168.1.102:8080/qualityserver/login.do";

public String doGet(String username, String password) {
    String getUrl = urlAddress + "?username=" + username + "&password=" + password;
    HttpGet httpGet = new HttpGet(getUrl);
    HttpClient hc = new DefaultHttpClient();
    try {
        HttpResponse ht = hc.execute(httpGet);
        if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity he = ht.getEntity();
            InputStream is = he.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String response = "";
            String readLine = null;
            while ((readLine = br.readLine()) != null) {
                response = response + readLine;
            }
            is.close();
            br.close();
            return response;
        } else {
            return "error";
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return "exception";
    } catch (IOException e) {
        e.printStackTrace();
        return "exception";
    }
}

public String doPost(String username, String password) {
    HttpPost httpPost = new HttpPost(urlAddress);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));

    HttpEntity he;
    try {
        he = new UrlEncodedFormEntity(params, "gbk");
        httpPost.setEntity(he);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    HttpClient hc = new DefaultHttpClient();
    try {
        HttpResponse ht = hc.execute(httpPost);
        if (ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity het = ht.getEntity();
            InputStream is = het.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String response = "";
            String readLine = null;
            while ((readLine = br.readLine()) != null) {
                response = response + readLine;
            }
            is.close();
            br.close();
            return response;
        } else {
            return "error";
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return "exception";
    } catch (IOException e) {
        e.printStackTrace();
        return "exception";
    }
}

對照之下差異很明顯:HttpClient 用 NameValuePair 集合處理 POST 參數,不必自己拼字串;用 StatusLine 判斷狀態碼;DefaultHttpClient 內建連線池管理。程式碼量相近,但可讀性與可維護性更好。

五、搭配 JSON 的完整往返

Servlet 端輸出 JSON:

resp.setContentType("text/json");
resp.setCharacterEncoding("UTF-8");

List<UserBean> list = toDo.queryUsers(mySession);
JSONArray array = new JSONArray();
for (UserBean bean : list) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("username", bean.getUserName());
        obj.put("password", bean.getPassWord());
    } catch (Exception e) { }
    array.add(obj);
}
pw.write(array.toString());

Android 端接收並解析:

String urlAddress = "https://192.168.1.102:8080/qualityserver/result.do";
String body = getContent(urlAddress);
JSONArray array = new JSONArray(body);
for (int i = 0; i < array.length(); i++) {
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        JSONObject obj = array.getJSONObject(i);
        userName = obj.getString("username");
        passWord = obj.getString("password");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    map.put("username", userName);
    map.put("password", passWord);
    listItem.add(map);
}

// 設定 adapter
SimpleAdapter simple = new SimpleAdapter(this, listItem,
        android.R.layout.simple_list_item_2,
        new String[] { "username", "password" },
        new int[] { android.R.id.text1, android.R.id.text2 });
listResult.setAdapter(simple);

// 帶超時設定的 GET
private String getContent(String url) throws Exception {
    StringBuilder sb = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpResponse response = client.execute(new HttpGet(url));
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();
    }
    return sb.toString();
}

六、現在該選哪一個

兩者都不再是首選。Android 4.4(API 19)起官方文件已明確建議改用 HttpURLConnection,Apache HttpClient 在 Android 5.1(API 22)被標記為 deprecated,Android 6.0 起更是從平台移除,需要自行把 jar 檔打包進專案才能用。

官方當初建議 HttpURLConnection 的理由是:它對多數應用只需 GET 與 POST 的場景夠用,且能與系統底層的連線管理、快取機制整合得更好,省電與省流量表現較佳。

若確實需要新版 HttpClient,可加入 org.apache.httpcomponents:httpclient 依賴並在 build.gradle 中啟用 useLibrary 'org.apache.http.legacy',但這只適合維護既有程式碼。

新專案的建議:優先考慮 HttpURLConnection 搭配 ExecutorService 處理非同步,或直接使用成熟網路庫——Volley 適合高頻小請求與圖片載入,Retrofit 搭配 OkHttp 則是目前的社群主流,它用註解宣告介面、自動處理 JSON 序列化,並與 RxJava、Kotlin 協程無縫整合,能省下大量樣板程式。

另外提醒一個與框架無關但常被忽略的問題:範例中把帳號密碼直接拼進 query string,等同在網路上裸奔。任何憑證傳輸都必須走 HTTPS,並避免出現在 URL 或日誌中。

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