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

Android 以 GET 方式發送 HTTP 請求的實作

編輯:關於 Android 程式設計

GET 是最直覺的請求方式:參數直接拼在網址後面,伺服器收到後回傳資料。在 Android 上用 HttpURLConnection 就能完成,程式碼量很少。

/**
 * 以 GET 方式發送請求
 *
 * @param username 使用者名稱
 * @param password 密碼
 * @return null 表示請求路徑有問題,text 為請求取得的資料
 */
public static String getRequest(String username, String password) {
    try {
        String path = "https://172.22.64.156:8080/0001AndroidWebService/LoginServlet?username="
                + URLEncoder.encode(username)
                + "&password="
                + URLEncoder.encode(password);

        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(500);
        conn.setRequestMethod("GET");

        int code = conn.getResponseCode();
        if (code == 200) {
            // 請求成功
            InputStream is = conn.getInputStream();
            String text = StreamUtil.readStream(is);
            return text;
        } else {
            // 請求失敗
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

幾個實務上的提醒

參數務必編碼。中文、空白與特殊符號若直接拼進網址會造成請求失敗,URLEncoder.encode() 是必要的。字元編碼建議明確帶上,例如 URLEncoder.encode(value, "UTF-8")。

逾時設定別太小。範例中的 500 毫秒在真實網路上很容易誤判超時,一般會設在數秒等級,並區分連線逾時與讀取逾時。

不要放在主線程。Android 4.0 之後網路請求寫在 UI 線程會直接拋出 NetworkOnMainThreadException,請搭配 AsyncTask、執行緒池或現代化的 HTTP 客戶端使用。

記得關閉串流與斷開連線。用 try-with-resources 或 finally 區塊收尾,能避免連線洩漏。

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