HTTP 協定核心特性
- 請求-回應模型:Client 發請求,Server 回應,完成即斷開 (短連接)。
- 無狀態:Server 不保留 Client 狀態,後續請求需攜帶完整資訊。
- HTTP/1.1 持久連接:單一 TCP 連接可傳輸多個請求,減少握手開銷。
GET vs POST 差異
| 特性 | GET | POST |
| 參數位置 | URL Query String (?a=1&b=2) | Request Body |
| 資料長度 | 受限 (~2KB) | 理論無上限 (視 Server 設定) |
| 安全性 | 明文可見 | 稍佳 (Body 不在 URL) |
| 適用場景 | 查詢、冪等操作 | 提交表單、上傳、狀態變更 |
Android 端實作範例 (HttpURLConnection)
GET 請求
String urlStr = "https://example.com/api?username=" + URLEncoder.encode(name, "UTF-8");
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line);
String response = sb.toString(); // JSON/XML 字串
// 解析 response...
}
conn.disconnect();
POST 請求 (含中文編碼)
String urlStr = "https://example.com/api/login";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true); // 允許輸出流
conn.setConnectTimeout(5000);
String postData = "username=" + URLEncoder.encode(user, "UTF-8") +
"&password=" + URLEncoder.encode(pwd, "UTF-8");
try (OutputStream os = conn.getOutputStream()) {
os.write(postData.getBytes("UTF-8"));
}
if (conn.getResponseCode() == 200) {
// 讀取回應同 GET
}
Servlet 端接收範例
// doGet
String username = request.getParameter("username");
// doPost
String username = request.getParameter("username"); // 同樣 API
response.getWriter().write("{\"status\":\"ok\"}");
最佳實踐建議
- 網路操作必須在子執行緒 (Thread, AsyncTask, RxJava, Coroutines) 執行。
- 生產環境建議使用成熟庫:OkHttp、Retrofit、Volley,處理連線池、快取、錯誤重試。
- HTTPS 為必備,生產環境勿使用明文 HTTP。