Cookie
In this chapter you will learn:
Get the cookie value
The following code gets the cookie value from the server. It looks
at the header name Set-Cookie
and uses regular
expression ;\\s*
to split the set cookie command.
import java.net.URL;
import java.net.URLConnection;
// ja va2 s . c o m
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http://java2s.com");
URLConnection conn = url.openConnection();
for (int i = 0;; i++) {
String headerName = conn.getHeaderFieldKey(i);
String headerValue = conn.getHeaderField(i);
if (headerName == null && headerValue == null) {
break;
}
if ("Set-Cookie".equalsIgnoreCase(headerName)) {
String[] fields = headerValue.split(";\\s*");
for (int j = 1; j < fields.length; j++) {
if ("secure".equalsIgnoreCase(fields[j])) {
System.out.println("secure=true");
} else if (fields[j].indexOf('=') > 0) {
String[] f = fields[j].split("=");
if ("expires".equalsIgnoreCase(f[0])) {
System.out.println("expires"+ f[1]);
} else if ("domain".equalsIgnoreCase(f[0])) {
System.out.println("domain"+ f[1]);
} else if ("path".equalsIgnoreCase(f[0])) {
System.out.println("path"+ f[1]);
}
}
}
}
}
}
}
The code above generates the following result.
Sending a Cookie to an HTTP Server
import java.net.URL;
import java.net.URLConnection;
// j av a 2s . c o m
public class Main {
public static void main(String[] argv) throws Exception {
URL url = new URL("http://hostname:80");
URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", "name1=value1; name2=value2");
conn.connect();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » URL URI