What are Cookies?
Cookies are small strings of data of the form name=value. These are delivered to the client via the header variables in an HTTP response. Upon receiving a cookie from a web server, the client application should store that cookie, returning it to the server in subsequent requests. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.
By having the server read information it sent the client previously, the site can provide visitors with a number of conveniences:

  1. Identifying a user during an e-commerce session.
  2. Avoiding username and password.
  3. Customizing a site as per user preferences.
  4. Focused advertising.
How to add Cookies to response header?
Cookie userCookie = new Cookie("user", "user_blr_2010");
userCookie.setMaxAge(60*60*24*365); // (Optional)
How to get Cookies from request?
Cookie[] cookies = request.getCookies();
Cookie cookie;
for(int i=0; i<cookies.length; i++) {
 cookie = cookies[i];
 out.println("<TR>\n" +
 " <TD>" + cookie.getName() + "\n" +
 " <TD>" + cookie.getValue());
How to find Cookies with Specified Names?

public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue) {
  for(int i=0; i<cookies.length; i++) {
    Cookie cookie = cookies[i];
    if (cookieName.equals(cookie.getName())) {
public static Cookie getCookie(Cookie[] cookies, String cookieName) {
  for(int i=0; i<cookies.length; i++) {
    Cookie cookie = cookies[i];
    if (cookieName.equals(cookie.getName()))

How to use Java.Net.* API to handle Cookies?

Setup URLConnection to the URL:
URL myUrl = new URL("http://www.testcookies.com");
URLConnection urlConn = myUrl.openConnection();

Header fields comes as Map so find the value which has key="Set-Cookie", and get that field:

String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
  if (headerName.equals("Set-Cookie")) {
    String cookie = urlConn.getHeaderField(i);

The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;), so if we want to find out first cookie:

cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

Related Posts


Post a Comment