How To Get Cookies In Httpurlconnection By Using Cookiestore?
In my Application class, I do the following: public class MyApplication extends Application { private static HttpURLConnection conn = null; public static CookieStore cookie
Solution 1:
Use this to set cookies.
First, set upcookieManager:
cookieManager = new java.net.CookieManager();
CookieHandler.setDefault(cookieManager);
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
Next, set cookies to HttpUrlConnection by setRequestProperty()
if (cookieManager.getCookieStore().getCookies().size() > 0) {
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
if (cookies != null) {
for (HttpCookie cookie : cookies) {
conn.setRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue());
}
}
}
Solution 2:
set cookie :
conn.setRequestProperty("Cookie", "cookieName=cookieValue; domain=www.test.com");
get cookie :
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get("Set-Cookie");
if(cookiesHeader != null){
String cookie = cookiesHeader.get(0);
HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
String name = httpCookie.getName();
String value = httpCookie.getValue();
String domain = httpCookie.getDomain();
}
Post a Comment for "How To Get Cookies In Httpurlconnection By Using Cookiestore?"