Maintaining session across http calls in Android
In my Android Project I was using old apache library for networking operations. There I used the BasicCookie() in HttpContext for maintaining sessions across the https calls. Now Google has deprecated the Apache Library and So I switched to URLConnection for networking. But I am not sure how I can set cookie in HttpsUrlConnection to maintain the session across the https calls. How can I set the same functionality in HttpURlConnection also.
I tried all these from this post, but didnt help. How to handle cookies in httpUrlConnection using cookieManager
Create a CookieManager member object in your Authentication class so you can access it from other Activities when you want to retrieve and use your cookie later.
//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);
}
}
In your other Activity where you want to set the retrieved cookie in your post request.
CookieManger cookieManager = MyAuthentication.mCookieManager;
//authentication code
//...
if(mCookieManager.getCookieStore().getCookies().size() > 0) {
urlConnection.setRequestProperty("Cookie",
TextUtils.join(";", mCookieManager.getCookieStore().getCookies()));
}
链接地址: http://www.djcxy.com/p/87920.html