How do browsers handle cookies?

How does the browser manage cookies? I mean, do I need to create a cookie?

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

I need an answer in Java.

+4
source share
4 answers

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

Using the Java Servlet API, you can create cookies with:

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

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

+3
source

If you want to create a mini browser with cookie state using the built-in java.net API, you can check out this tutorial: http://www.hccp.org/java-net-cookie-how-to.html . It shows how Java can connect to a URL, view response headers for receiving cookies, and how to set cookies in a request.

Code example:

  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(); 
+1
source

Assuming you are running a server and running in a Servlet environment (Tomcat, Jetty), you want to see getCookies and similar cookies in the response.

0
source

If you want to automate the website viewing from the client’s point of view, instead of doing it manually, I would use a framework such as JWebUnit , which is based on HtmlUnit , but even higher level and easier to use. You do not need to worry about cookies, but you have access to them if you need to examine them.

I know that this does not directly answer your question about how the browser handles cookies, but I hope this helps!

0
source

Source: https://habr.com/ru/post/1338559/


All Articles