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

Android 的四種常見網絡請求方式詳解

編輯:關於 Android 程式設計

行動應用幾乎一定要和伺服器打交道,發請求就成了基本功。這裡梳理四種常見做法,兩兩一組:Java 原生的 HttpURLConnection,以及 Apache 的 HttpClient,各自都有 GET 與 POST 兩種形式。示例代碼都放在單元測試裡跑,方便直接驗證。

一、HttpURLConnection 的 GET 請求

參數直接拼在 URL 上,打開連接、設定超時、判斷回應碼即可。

// GET 方式請求
public static void requestByGet() throws Exception {
    String path = "https://www.jb51.net/logins.jsp?id=helloworld&pwd=android";
    URL url = new URL(path);
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setConnectTimeout(5 * 1000); // 連接超時
    urlConn.connect();
    if (urlConn.getResponseCode() == HTTP_200) {
        byte[] data = readStream(urlConn.getInputStream());
        Log.i(TAG_GET, "Get方式請求成功,返回數據如下:");
        Log.i(TAG_GET, new String(data, "UTF-8"));
    } else {
        Log.i(TAG_GET, "Get方式請求失敗");
    }
    urlConn.disconnect();
}

二、HttpURLConnection 的 POST 請求

POST 有幾個必須設定的開關:允許輸出、關閉緩存、請求方法改為 POST,並通過 DataOutputStream 把參數寫出去。

// POST 方式請求
public static void requestByPost() throws Throwable {
    String path = "https://www.jb51.net/logins.jsp";
    // 參數需先做 URL 編碼
    String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
                  + "&pwd=" + URLEncoder.encode("android", "UTF-8");
    byte[] postData = params.getBytes();

    URL url = new URL(path);
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    urlConn.setConnectTimeout(5 * 1000);
    urlConn.setDoOutput(true);   // POST 必須允許輸出
    urlConn.setUseCaches(false); // POST 不使用緩存
    urlConn.setRequestMethod("POST");
    urlConn.setInstanceFollowRedirects(true);
    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    urlConn.connect();

    DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
    dos.write(postData);
    dos.flush();
    dos.close();

    if (urlConn.getResponseCode() == HTTP_200) {
        byte[] data = readStream(urlConn.getInputStream());
        Log.i(TAG_POST, "Post請求方式成功,返回數據如下:");
        Log.i(TAG_POST, new String(data, "UTF-8"));
    } else {
        Log.i(TAG_POST, "Post方式請求失敗");
    }
}

三、HttpGet

Apache 這一路的寫法更精簡,一行 execute 就把請求發出去了。

// HttpGet 方式請求
public static void requestByHttpGet() throws Exception {
    String path = "https://www.jb51.net/logins.jsp?id=helloworld&pwd=android";
    HttpGet httpGet = new HttpGet(path);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResp = httpClient.execute(httpGet);
    if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
        String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
        Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回數據如下:");
        Log.i(TAG_HTTPGET, result);
    } else {
        Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");
    }
}

四、HttpPost

參數用 NameValuePair 列表承載,封裝成 UrlEncodedFormEntity 後掛到請求上。

// HttpPost 方式請求
public static void requestByHttpPost() throws Exception {
    String path = "https://www.jb51.net/";
    HttpPost httpPost = new HttpPost(path);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("id", "helloworld"));
    params.add(new BasicNameValuePair("pwd", "android"));
    HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
    httpPost.setEntity(entity);

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResp = httpClient.execute(httpPost);
    if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
        String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
        Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回數據如下:");
        Log.i(TAG_HTTPGET, result);
    } else {
        Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");
    }
}

以上只是核心片段,測試時在測試類中調用對應方法即可。兩套方案各有取捨:HttpURLConnection 屬於標準庫、實現輕量,有利於省電省內存;HttpClient 的 API 更省心,但新版 Android 已不再推薦。新專案建議直接上 OkHttp 或 Retrofit。

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