Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLConnection with Cookies?

Tags:

I'm trying to make a URLConnection that supports cookies. According to the documentation I can use:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

I couldn't get this code to work, then I saw this only works for API 9 (2.3). However, I don't get an error using CookieManager in an older emulator, CookieManager exists, but can't be constructed. Is there any way to make this work for earlier versions? I tried:

            cookieManager.setAcceptCookie(true);
            URLConnection con = u.openConnection();

            con.setRequestProperty("Cookie", cookieManager.getInstance().getCookie(url););
            con.setDoOutput(true);
            con.connect();
            String addCookie = con.getHeaderField("Set-Cookie");
            System.out.println(con.getHeaderFields().toString());
            if (addCookie!=null) {
                cookieManager.getInstance().setCookie(url, addCookie);
            }

but this doesn't work.

like image 423
NoBugs Avatar asked Jun 15 '11 07:06

NoBugs


People also ask

How do I add cookies to HttpURLConnection?

openConnection(); Create a cookie string: String myCookie = "userId=igbrown"; Add the cookie to a request: Using the setRequestProperty(String name, String value); method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

When should I use HttpURLConnection?

The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. It sets whether HTTP redirects (requests with response code) should be automatically followed by HttpURLConnection class.


1 Answers

I was able to enable cookies using Ian Brown's CookieManager class: http://www.hccp.org/java-net-cookie-how-to.html

I renamed it to IansCookieManager, set a class variable _CM = new IansCookieManager, now it's simple:

            URLConnection conn = u.openConnection();
            _CM.setCookies(conn);
            conn.connect();
            _CM.storeCookies(conn);
            ... 
like image 127
NoBugs Avatar answered Sep 24 '22 01:09

NoBugs