完成 Android 客戶端後,需建立伺服器接收資料。最簡單路徑:Java + Tomcat + Servlet + MySQL,無需複雜框架即可快速驗證流程。
Android App (HttpURLConnection/OkHttp/Retrofit)
↓ HTTP POST/GET (JSON)
Tomcat Servlet (doPost/doGet)
↓ JDBC
MySQL Database
@WebServlet("/api/data")
public class DataServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 1. 讀取 JSON
StringBuilder sb = new StringBuilder();
try (BufferedReader br = req.getReader()) {
String line;
while ((line = br.readLine()) != null) sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
// 2. 寫入資料庫
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO records (content, created_at) VALUES (?, NOW())")) {
ps.setString(1, json.getString("content"));
ps.executeUpdate();
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().write("{\"status\":\"success\"}");
} catch (SQLException e) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
}
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject().put("content", "測試資料");
RequestBody body = RequestBody.create(json.toString(), MediaType.get("application/json"));
Request request = new Request.Builder()
.url("https://your-server:8080/api/data")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onResponse(Call call, Response response) {
Log.d("Server", response.body().string());
}
@Override public void onFailure(Call call, IOException e) {
Log.e("Server", "請求失敗", e);
}
});
HikariCP 或 Druid。Spring Boot、MyBatis、JPA 簡化開發。CompletableFuture、訊息佇列(RabbitMQ/Kafka)削峰填谷。先跑通最簡流程,再按需求逐步重構,是穩健的工程實踐。