編輯:關於 Android 開發
承接上一篇〈Android 採用 get 方式提交數據到服務器〉,這次我們在同一個專案上加入 POST 版本,讓兩種請求方式並排比較。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入用戶名"
android:inputType="text" />
<EditText android:id="@+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入密碼"
android:inputType="textPassword" />
<Button android:onClick="LoginByGet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GET方式登錄" />
<Button android:onClick="LoginByPost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="POST方式登錄" />
</LinearLayout>
package com.wuyudong.loginclient;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd);
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/** GET 方式 */
public void LoginByGet(View view) {
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用戶名密碼不能為空", 0).show();
} else {
// 參數直接拼在網址後面
String path = "https://169.254.168.71:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String result = new String(bos.toByteArray());
is.close();
Toast.makeText(this, result, 0).show();
} else {
Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "請求失敗,請檢查 logcat 日誌控制台", 0).show();
}
}
}
/** POST 方式 */
public void LoginByPost(View view) {
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用戶名密碼不能為空", 0).show();
} else {
try {
String path = "https://169.254.168.71:8080/web/LoginServlet";
// 1. 定義請求 url
URL url = new URL(path);
// 2. 建立一個 http 連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3. 設置請求參數
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String data = "username=" + name + "&password=" + pwd;
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setConnectTimeout(5000); // 連接超時
conn.setReadTimeout(5000); // 讀取超時
// 4. 一定要記得設置,把數據以流的方式寫給服務器
conn.setDoOutput(true);
conn.getOutputStream().write(data.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String result = new String(bos.toByteArray());
is.close();
Toast.makeText(this, result, 0).show();
} else {
Toast.makeText(this, "請求失敗,失敗原因: " + code, 0).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "請求失敗,請檢查 logcat 日誌控制台", 0).show();
}
}
}
}
1. 參數位置:GET 把參數接在網址後(?username=...&password=...);POST 則透過要求主體(request body)傳送,網址保持乾淨。
2. 請求方法設定:conn.setRequestMethod("POST"),字串必須大寫。
3. Content-Type:POST 表單需明確宣告 application/x-www-form-urlencoded,伺服器才知道怎麼解析 body。
4. setDoOutput(true):這是最容易漏掉的一步。少了它,getOutputStream() 寫入的內容不會真正送出,伺服器收到的參數會是空的。
5. 逾時設定:setConnectTimeout() 與 setReadTimeout() 建議一定要設。不設的話在網路不佳時會無限期等待,實務上非常容易踩到 ANR。
6. 編碼問題:範例中的中文若出現亂碼,通常是兩端編碼不一致所致。正式專案應統一以 UTF-8 編碼,並對每個參數值做 URL Encode。
7. 安全性:GET 的參數會留在瀏覽器歷史、代理伺服器與存取日誌裡,密碼等敏感資訊不該走 GET。但 POST 本身也只是「不顯示在網址列」而已,傳輸內容仍是明文——真正解決之道是全程使用 HTTPS。
另外提醒,範例中的 StrictMode 設定只是為了讓教學程式碼能直接跑起來。正式環境請把網路操作移到工作執行緒,並在 HttpURLConnection 使用完畢後確實關閉串流,或改用 OkHttp、Retrofit 等成熟客戶端來處理連線管理與重試邏輯。
Android 數據存儲實戰:SharedPreferences 與文件讀寫
前言 大家好,本篇我們一起動手做一個帶註冊、登錄功能的備忘錄小應用,在實戰中掌握 SharedPreferences 的基本用法、Android 中常見的文件操作方法,順
Android Studio 1.3 新版 NDK 支援上手:告別 Android.mk 的 C++ 開發流程
背景:Google 終於把 NDK 收進官方工具鏈 2015 年 5 月底的 Google I/O 大會上,Google 宣布 Android Studio 1.3 將整
Android JNI 入門:概念、用途與 NDK 介紹
Android JNI 入門:概念、用途與 NDK 介紹 JNI 簡介 JNI(Java Native Interface)即 Java 的本地介面,是 Java 眾多開
Android 那些不常用卻很實用的控件盤點
Android 那些不常用卻很實用的控件盤點 Android 提供了豐富的內置控件,其中有一些並不常被提及,但在特定場景下能省下不少功夫。下面盤點幾個: AutoComp