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

Android 提交資料:GET 與 POST 的底層差異一次講清

編輯:關於 Android 程式設計

GET:把參數黏在網址後面

GET 提交最直觀,參數用 ? 起頭、以 & 分隔,直接接在網址後方。

final String path = "https://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;

送出請求的寫法和一般 GET 沒有兩樣:

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
    // 處理回應
}

但有一個細節容易忽略:瀏覽器送出請求時會自動對參數做 URL 編碼,我們自己拼字串時不會。一旦欄位裡出現中文或空白,就必須手動編碼,否則伺服器收到的會是亂碼。

String path = "https://192.168.1.104/Web/servlet/CheckLogin?name="
        + URLEncoder.encode(name) + "&pass=" + pass;

另外提醒,GET 的長度受網址限制,密碼直接暴露在網址上也不安全,正式環境不建議用 GET 傳敏感資料。

POST:用串流把資料寫給伺服器

POST 把參數放進 request body,以串流方式寫出。跟 GET 相比,通訊協定標頭多出兩個必填欄位:

  • Content-Type: application/x-www-form-urlencoded——說明 body 的 MIME 類型。
  • Content-Length——說明 body 的位元組長度。

這兩個標頭必須自己補上,方法是先組好要送的字串:

String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");

接著要主動打開寫入的通道,預設情況下 HttpURLConnection 是不允許輸出資料的:

conn.setDoOutput(true);

然後取得輸出串流,把資料寫進去:

OutputStream os = conn.getOutputStream();
os.write(data.getBytes());

兩者該怎麼選

GET 走的是網址,參數攤在明面上,適合查詢類、可快取、可被書籤收藏的請求;POST 走的是 body,容量不受網址長度限制,適合新增資料、上傳較長內容或傳送敏感欄位。兩者本質上都是 HTTP 請求,差別在資料放哪裡、以及伺服器端怎麼解讀。

最後别忘了:寫完 OutputStream 記得關閉,並在 Content-Length 上填「位元組數」而非「字元數」。若參數含中文,用 data.getBytes("UTF-8").length 才是正確長度。

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