在您的Authentication類中創建一個CookieManager成員對象,以便您可以在稍後檢索並使用您的Cookie時從其他活動訪問它。
//In MyAuthentication class
static CookieManager mCookieManager = new CookieManager();
static String COOKIE_HEADER = "Set-Cookie";
//authentication code
//...
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
Map<String, List<String>> headers = urlConnection.getHeaderFields();
List<String> cookies = headers.get(COOKIE_HEADER);
for(String cookie: cookies){
HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
mCookieManager.getCookieStore().add(null, httpCookie);
}
}
在您希望在您的發佈請求中設置檢索到的cookie的其他Activity中。
CookieManger cookieManager = MyAuthentication.mCookieManager;
//authentication code
//...
if(mCookieManager.getCookieStore().getCookies().size() > 0) {
urlConnection.setRequestProperty("Cookie",
TextUtils.join(";", mCookieManager.getCookieStore().getCookies()));
}