Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access / save cookies in Java

Tags:

java

cookies

save

I am writing some software in Java.

I am testing the cookie managment functionality but I can't seem to get cookies working. I wrote a quick PHP that drops a cookie, and I tested that in my browser and the cookie drops fine.

However, take a look at this code:

    CookieManager cManager = new CookieManager();
    CookieHandler.setDefault(cManager);
    try
    {

        URL url = new URL("http://localhost/_techfactory/apage.php");
        URLConnection connection = url.openConnection();
        CookieStore cookieJar = cManager.getCookieStore();
        List<HttpCookie> cookies = cookieJar.getCookies();
        for ( HttpCookie cookie : cookies)
        {
            System.out.print(cookie);
        }
        Boolean isittrue = cookies.isEmpty();
        System.out.print(isittrue);
        BufferedReader bin = new BufferedReader ( new InputStreamReader(connection.getInputStream()));
        String line;
        while ( ( line = bin.readLine()) != null )  
        System.out.print(line);

    }
    catch ( Exception e )
    {
        System.out.println(e);
    }

This, although being syntactically correct, doesn't output anything, except the HTML from the page. Now by all accounts, the CookieManager implementaiton is a concrete implementation of CookieHandler, CookiePolicy and CookieStore. However, it just refuses to work for me, what I am I doing wrong?

like image 728
anomalousmaterials Avatar asked Aug 25 '26 03:08

anomalousmaterials


1 Answers

You need to read the HTTP header fields before checking the cookie store, and calling openConnection() does not read the HTTP headers. See the first few lines of the javadoc.

If you need the cookies during processing, calling getInputStream() connects and parses the header fields, as will some of the other methods in URLConnection.

like image 66
Michael Brewer-Davis Avatar answered Aug 26 '26 16:08

Michael Brewer-Davis