編輯:關於 Android 開發
行動應用幾乎都要跟後端打交道。本文從零開始搭建一個最簡單的登入場景:先用 Servlet 模擬伺服器端,再用 Android 客戶端以 GET 方式把帳號密碼送過去,並處理回應。
新建動態 Web 專案,撰寫 Servlet:
package com.wuyudong.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("用戶名:" + username);
System.out.println("密碼:" + password);
if ("wuyudong".equals(username) && "123".equals(password)) {
response.getOutputStream().write("login success".getBytes());
} else {
response.getOutputStream().write("login failed".getBytes());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
再補一個 JSP 頁面方便用瀏覽器自測:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登錄頁面</title> </head> <body> <form action="LoginServlet" method="get"> 用戶名:<input name="username" type="text"><br> 密碼:<input name="password" type="password"><br> <input type="submit"> </form> </body> </html>
<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="login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登錄" />
</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.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);
}
public void login(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 {
// 模擬 http 請求,提交數據到服務器
String path = "https://169.254.168.71:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
try {
URL url = new URL(path);
// 建立一個 http 連接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 設置請求方式,注意 GET 字母一定要大寫
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(); // 200 OK / 404 / 503
if (code == 200) {
InputStream is = conn.getInputStream();
// 把 is 的內容轉換為字符串
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();
}
}
}
}
別忘了在 AndroidManifest.xml 加上網路權限:
<uses-permission android:name="android.permission.INTERNET"/>
直接執行,點下按鈕後會看到這樣的錯誤:
android.os.NetworkOnMainThreadException
從 Android 3.0(Honeycomb)開始,系統禁止在主執行緒(UI Thread)進行網路 I/O,以避免畫面卡頓甚至 ANR。快速繞過的方式是在 onCreate() 中放寬政策:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
但這只是讓程式跑得起來,並不是好做法。正式專案應該把網路請求放進 AsyncTask、Thread、Kotlin 協程或 RxJava 等工作執行緒,透過 Handler 或相應機制回主執行緒更新 UI。
參數直接拼在網址後面,意味著:中文與特殊字元必須先做 URL Encode;長度受伺服器與代理的限制;最關鍵的是密碼會明文出現在網址與伺服器存取日誌中。所以登入這類敏感操作,實務上都應該改用 POST 並全程走 HTTPS。下一篇我們就把 POST 版本做出來做對照。
Android 複製文字到剪貼板:最簡短實作與相容性提醒
複製文字到剪貼板 Android 中要把文字放入系統剪貼板,核心是取得 ClipboardManager,再呼叫 setText()。為了相容舊版本,實務上常使用 and
HelloCharts 線形圖入門
HelloCharts 線形圖入門 HelloCharts 是一個輕量化的 Android 圖表框架,支援線形圖、柱狀圖、圓餅圖等多種圖表。本文以線形圖為例,說明如何建立
重新思考 Android Activity 設計:從常見抱怨到優化方向
Activity 設計帶來的開發痛點 Android 的 Activity 設計強調執行期獨立性。每個 Activity 都必須在 AndroidManifest.xml
Linux 死鎖排查實戰:用 pstack 與 gdb 精準定位交叉持鎖
死鎖(deadlock)指的是兩個或多個線程在執行過程中互相爭奪資源而形成的循環等待:沒有外力介入,誰都推不進去。最典型的就是交叉持鎖——線程 1 鎖住 A 等 B,線程