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

Android 學習:使用 POST 方式提交資料到伺服器

編輯:關於 Android 程式設計

GET 方式會把資料作為網址的一部分提交,且對長度有限制。POST 方式則類似,參數同樣經過 URL 編碼,但變數名稱與值不放在網址中,而是放在實際的 HTTP 請求訊息內部傳送。

設定 POST 請求

透過 HttpURLConnection 設定請求方式與相關標頭:

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("POST"); // 以 POST 請求方式提交
urlConnection.setDoInput(true); // 讀取資料
urlConnection.setDoOutput(true); // 向伺服器寫資料
byte[] myData = stringBuilder.toString().getBytes();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(myData.length));

封裝 HttpUtils 工具類別

以下重點說明 sendPostMessage 方法:先把 Map 中的參數以 key=value& 的形式拼接並編碼,再透過輸出流寫入伺服器,最後讀取回應:

// 拼接並編碼參數
for (Map.Entry<String, String> entry : params.entrySet()) {
  stringBuilder.append(entry.getKey()).append("=")
    .append(URLEncoder.encode(entry.getValue(), encode)).append("&");
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
// 寫入資料
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(myData, 0, myData.length);
outputStream.close();
// 取得回應
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
  return changeInputStream(urlConnection.getInputStream(), encode);
}

其中 changeInputStream 負責把輸入流讀進 ByteArrayOutputStream,再以指定編碼轉成字串。

伺服器端 Servlet

伺服器端建立一個繼承 HttpServlet 的 LoginAction,在 doPost 中設定編碼後,用 request.getParameter 取得 username 與 password,比對是否正確並回傳結果:

response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
if (userName.equals("admin") && passWord.equals("123456")) {
  out.print("login successful!");
} else {
  out.print("login failed");
}

別忘了在 web.xml 中設定 servlet 與 servlet-mapping,讓 /servlet/LoginAction 能正確對應到 LoginAction。這樣就完成了一個以 POST 提交並由 Servlet 處理的完整範例。

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