版面佈局 (登入頁)
<EditText android:id="@+id/editTextUserName" android:hint="帳號" android:inputType="text" ... />
<EditText android:id="@+id/editTextPassword" android:hint="密碼" android:inputType="textPassword" ... />
<Button android:id="@+id/btnLogin" android:text="登入" ... />
<TextView android:id="@+id/textViewLoginMsg" android:visibility="gone" android:textColor="#FF0000" ... />
網路請求邏輯 (登入按鈕點擊)
Button btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(v -> {
String username = etUser.getText().toString().trim();
String password = etPwd.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) return;
// 必須在子執行緒執行網路請求
new Thread(() -> {
try {
HttpClient httpClient = new DefaultHttpClient(); // 旧 API 示範,建議用 OkHttp
HttpPost httpPost = new HttpPost("https://your-server.com/login");
List params = new ArrayList<>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String jsonStr = EntityUtils.toString(response.getEntity());
// 解析 JSON
JSONObject json = new JSONObject(jsonStr);
boolean success = json.optBoolean("loginStatus", false);
String msg = json.optString("outMessage", "");
runOnUiThread(() -> {
if (success) {
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("username", msg); // msg 可能為用戶名/token
startActivityForResult(i, REQUEST_CODE);
finish();
} else {
tvMsg.setVisibility(View.VISIBLE);
tvMsg.setText(msg);
}
});
} else {
runOnUiThread(() -> tvMsg.setText("網絡錯誤: " + statusCode));
}
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(() -> tvMsg.setText("請求異常: " + e.getMessage()));
}
}).start();
});
伺服器端回應格式 (JSON)
// 成功
{"loginStatus": true, "outMessage": "user_token_or_name"}
// 失敗
{"loginStatus": false, "outMessage": "帳號或密碼錯誤"}
重要遷移提醒
- HttpClient / DefaultHttpClient / HttpPost / NameValuePair 已在 API 22 棄用,API 23 移除。
- 現代專案請使用 OkHttp + Retrofit / Volley / Coroutines + Ktor。
- OkHttp 同等邏輯極簡:
OkHttpClient client = new OkHttpClient();
RequestBody form = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
Request request = new Request.Builder().url(url).post(form).build();
client.newCall(request).enqueue(new Callback() {
@Override public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
// 解析 JSON 並 runOnUiThread 更新 UI
}
@Override public void onFailure(Call call, IOException e) { /* 處理失敗 */ }
});
安全建議
- 生產環境**強制 HTTPS**,防止密碼明文傳輸。
- 密碼**不應明文傳輸**,建議採用 OAuth2 / JWT / SRP / 加密傳輸。
- 防止暴力破解:伺服器端限制嘗試次數、驗證碼、帳號鎖定。