How to access cookies in Java

I am writing some kind of software in Java.

I am testing cookie management functionality, but I cannot get cookies to work. I wrote a quick PHP that throws a cookie and I tested it in my browser and the cookie fell perfectly.

However, 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 syntactically correct, displays nothing but HTML from the page. For all accounts, the cookieManager implementation now implements the specific implementation of CookieHandler, CookiePolicy, and CookieStore. However, he just refuses to work for me, what am I doing wrong?

+3
source share
1 answer

HTTP, cookie, openConnection() HTTP. javadoc.

cookie , getInputStream() , URLConnection.

+1

All Articles