Tutorials : Recipes for Cookie Management in J2SEs Tiger and Mustang :

Extracting a Cookie from the HTTP Response

As stated earlier, a cookie is marked by the Set-Cookie header, which you place into the HTTP response. To write a Java app that extracts cookies from an HTTP response, you must detect this header, from which you will extract the name=value pairs. This can be done in at least two ways:
  1. The first method is to use the getHeaderFieldKey and getHeaderField methods from the HttpURLConnection class:
    • public String getHeaderFieldKey(int n): This method returns the key (the name) for the nth header field, where n>=0.
    • public String getHeaderField(int n): This method returns the value for the nth header field, where n>=0.
    Listing 1 shows the HttpURLConnection class in an application that extracts cookies from a HTTP response.
  2. The second method is to use a java.util.Map object with the URLConnection.getHeaderFields method. Obviously, using java.util.Map is very convenient because it facilitates an easy way to store key=value pairs. In fact, the getHeaderFields method returns a java.util.Map object:
    public Map<String,List<String>> getHeaderFields()
    
    Listing 2 demonstrates the alternate method of extracting cookies from an HTTP response.

Extracting a Cookie from the HTTP Response

The easiest way to place a cookie in an HTTP request is to call the URLConnection.setRequestProperty method:
public void setRequestProperty(String key, String value)
This method places a new "entry" in the HTTP request header. In this case, the key argument will be Cookie and the value argument will be a string of type name=value pairs separated by ";".

Listing 3 shows you how to send a cookie to the server using the setRequestProperty method.

Remember if the above solution fails, it's better to use a socket base connection.

Home / Articles / Recipes for Cookie Management in J2SEs Tiger and Mustang / 1 / 2 / Next Page

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.