简体   繁体   中英

Handling Cookies while working with URL class in java

I'm writing a program to send a POST method to a website and then login. But for a successful login the website needs to store and retrieve cookies.

This is the code which I'm using to send POST method to the website:

        URL url = new URL(link);
        CookieHandler.setDefault(new CookieManager());

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(values);
        writer.flush();
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null)
        {
            System.out.println(line);
        }
        writer.close();
        reader.close();

So how can I handle the cookies?

The line

CookieHandler.setDefault(new CookieManager());

sets a global variable that causes the connection to automatically handle cookies - internally - just before the connection sends the request to the server and just after it receives the response. It does so for all your HTTP requests.

You don't have to do a thing besides setting up the default cookie handler.

While this global variable and behavior can be handy in many cases, it can cause problems in other cases, such as when you want to establish multiple separate sessions with the same server. In the latter cases, the cookies for each session should be separate, but they all end up in the same global cookie store and overwrite each other.

If you need to manage separate cookies for different sessions or threads, see my answer here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM