HttpClient 實現HttpContext + CookieStore// LoginServlet: 接收 info 參數存入 Session
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
session.setAttribute("info", req.getParameter("info"));
resp.getWriter().write("OK");
}
}
// InfoServlet: 讀取 Session 中的 info
@WebServlet("/info")
public class InfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
String info = (String) req.getSession().getAttribute("info");
resp.getWriter().write(info != null ? info : "null");
}
}
public class MainActivity extends AppCompatActivity {
private AndroidHttpClient httpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpClient = AndroidHttpClient.newInstance("CookieDemo/1.0");
findViewById(R.id.btn_test).setOnClickListener(v -> new Thread(this::testCookieFlow).start());
}
private void testCookieFlow() {
try {
// 1. 創建攜帶 CookieStore 的上下文
HttpContext context = new BasicHttpContext();
context.setAttribute(HttpClientContext.COOKIE_STORE, new BasicCookieStore());
// 2. 登錄請求 (POST)
HttpPost loginPost = new HttpPost("https://10.0.2.2:8080/login");
loginPost.setEntity(new UrlEncodedFormEntity(
Collections.singletonList(new BasicNameValuePair("info", "你好 世界!!")), "UTF-8"));
HttpResponse loginResp = httpClient.execute(loginPost, context);
EntityUtils.consume(loginResp.getEntity());
Log.d("CookieDemo", "登錄響應: " + EntityUtils.toString(loginResp.getEntity()));
// 3. 獲取信息請求 (GET) —— 同一 context 自動攜帶 Cookie
HttpGet infoGet = new HttpGet("https://10.0.2.2:8080/info");
HttpResponse infoResp = httpClient.execute(infoGet, context);
String info = EntityUtils.toString(infoResp.getEntity());
Log.d("CookieDemo", "獲取信息: " + info); // 應輸出 "你好 世界!!"
EntityUtils.consume(infoResp.getEntity());
} catch (IOException e) {
Log.e("CookieDemo", "請求失敗", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (httpClient != null) httpClient.close(); // 必須關閉,否則無法創建新實例
}
}
| 特性 | DefaultHttpClient | AndroidHttpClient |
|---|---|---|
| 主線程執行 | 允許 (但會拋 NetworkOnMainThreadException) | **直接拋異常禁止** |
| 實例創建 | new DefaultHttpClient() | AndroidHttpClient.newInstance(userAgent) |
| Cookie 默認 | 啟用 | **禁用**,需手動附加 CookieStore |
| 資源釋放 | getConnectionManager().shutdown() | close() |
SharedPreferences 或 CookieJar (OkHttp) 實現冷啟動免登理解 HttpContext 作為請求上下文載體,攜帶 CookieStore 實現會話保持,是舊版 Android 網絡開發的核心模式。