首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

AndroidHttpClient Cookie 管理實戰:自動登錄與會話保持

     編輯:Java 程式設計入門

為什麼選 AndroidHttpClient?

  • 針對 Android 系統優化的 HttpClient 實現
  • **主線程禁用網絡請求**,強制異步,避免 ANR
  • 默認**關閉 Cookie**,需顯式管理 HttpContext + CookieStore

服務端模擬:兩個 Servlet

// 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");
    }
}

Android 客戶端完整實現

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(); // 必須關閉,否則無法創建新實例
    }
}

關鍵差異對比

特性DefaultHttpClientAndroidHttpClient
主線程執行允許 (但會拋 NetworkOnMainThreadException)**直接拋異常禁止**
實例創建new DefaultHttpClient()AndroidHttpClient.newInstance(userAgent)
Cookie 默認啟用**禁用**,需手動附加 CookieStore
資源釋放getConnectionManager().shutdown()close()

最佳實踐建議

  1. 單例模式管理 Client:Application 級單例,避免重複創建連接管理器
  2. 持久化 CookieStore:配合 SharedPreferences 或 CookieJar (OkHttp) 實現冷啟動免登
  3. 遷移到 OkHttp:Google 已棄用 HttpClient,**新項目請直接使用 OkHttp + CookieJar**,API 更現代、支持 HTTP/2、連接池更高效

理解 HttpContext 作為請求上下文載體,攜帶 CookieStore 實現會話保持,是舊版 Android 網絡開發的核心模式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved