Java Reference
In-Depth Information
The
str
variable will hold the header names as they are read in. The variable
n
will
keep count of which header we are currently processing.
String str;
int n = 1;
The
do/while
loop will look until a
null
header is found. A
null
header indicates
that there are no more headers to read. Each header is read and checked to see if it is a
Set-Cookie
header.
do
{
str = http.getHeaderFieldKey(n);
if( (str!=null) && str.equalsIgnoreCase("Set-Cookie"))
{
If it is a
Set-Cookie
header, then the cookie is parsed and saved in cookie map. The
cookie map is a Java
Map
collection that maps cookie names to their values.
str = http.getHeaderField(n);
StringTokenizer tok = new StringTokenizer(str,"=");
String name = tok.nextToken();
String value = tok.nextToken();
map.put(name, value);
}
Next, the
loadCookies
method moves on to the next header.
n++;
} while(str!=null);
This process continues until all headers have been processed.
Sending Cookies from the Browser
Once the cookies have been loaded by the
loadCookies
method, they must be
attached to future server requests. This is the job of the
saveCookies
method. The
cookie name-value pairs for a given site will be concatenated together. The
saveCookies
method begins by declaring a
StringBuilder
that will hold the Cookie header until it
is completely constructed.
StringBuilder str = new StringBuilder();
Next, we iterate over all of the cookie names. As the “for each” loop passes over each
cookie in the collection the
key
variable will hold each cookie's name.
Set<String> set = map.keySet();
for(String key:set)
{