Diptopol Dam
Diptopol Dam

Reputation: 815

How do browsers handle cookies?

How does a browser manage cookies? I mean, does it have to create cookie the object?

Motivation: I want to log in to a cookie site. Nowadays cookies are not only name and value - they also contain domain, expiry date, etc.

I need the answer in Java prospective.

Upvotes: 5

Views: 2132

Answers (4)

Rui Gonçalves
Rui Gonçalves

Reputation: 1375

If what you want is to build a mini-browser with cookie state using java.net built-in API, you can check out this tutorial: http://www.hccp.org/java-net-cookie-how-to.html. It shows how can Java connect to a URL, go through response headers to fetch cookies, and how to set cookies in a request.

Some example code:

    System.out.println("GET: " + url);

    // create and open url connection for reading
    URL urlObj = new URL(url);
    URLConnection conn = urlObj.openConnection();

    // set existing cookies
    conn.setRequestProperty("Cookie", myGetSavedCookies(url));

    // connect
    conn.connect();

    // loop through response headers to set new cookies
    myAddSavedCookies(conn.getHeaderFields().get("Set-Cookie"));

    // read page
    Scanner sc = new Scanner(conn.getInputStream());
    while (sc.hasNextLine())
        out.write(sc.nextLine());
    sc.close();

Upvotes: 1

Tyler Holien
Tyler Holien

Reputation: 4951

If you are looking to automate browsing a web site from the client perspective, instead of doing it by hand, I would use a framework like JWebUnit, which is based on HtmlUnit but is even higher-level and easier to use. You don't have to worry about cookies, but you have access to them if you need to examine them.

I know this doesn't directly answer your question of how the browser handles cookies, but I hope it helps!

Upvotes: 0

David W
David W

Reputation: 945

Assuming that you are working on the server and working in a Servlet environment (Tomcat, Jetty), then you want to look at getCookies and the similar set cookies in the response.

Upvotes: 0

Bozho
Bozho

Reputation: 597076

Whenever a browser receives a response containing a specific cookie header, it creates a cookie.

With the java servlet API you can create cookies by:

Cookie cookie = new Cookie();
cookie.setName(); // setValue, setMaxAge, setPath, etc.
response.addCookie(cookie);

On subsequent requests the browser sends the cookies to the server. Again, with the servlet API, you can obtain the current cookies by calling request.getCookies()

Upvotes: 3

Related Questions