开发者

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 dat开发者_高级运维e, etc.

I need the answer in Java prospective.


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()


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();


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.


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!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜