开发者

How to access / save cookies in Java

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 fo开发者_运维问答r me, what I am I doing wrong?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜