1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| class CookiesInJava {
HashMap theCookies = new HashMap();
public URLConnection writeCookies
(URLConnection urlConn, boolean printCookies){
String cookieString = "";
Enumeration keys = theCookies.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
cookieString += key + "=" + theCookies.get(key);
if (keys.hasMoreElements())
cookieString += "; ";
}
urlConn.setRequestProperty("Cookie", cookieString);
if (printCookies)
System.println("Wrote cookies:\n " + cookieString);
return urlConn;
}
public void readCookies(URLConnection urlConn, boolean printCookies,
boolean reset){
if (reset)
theCookies.clear();
int i=1;
String hdrKey;
String hdrString;
String aCookie;
while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
if (hdrKey.equals("Set-Cookie")) {
hdrString = urlConn.getHeaderField(i);
StringTokenizer intGst = new StringTokenizer(hdrString,",");
while (intGst.hasMoreTokens()) {
String s = intGst.nextToken();
aCookie = s.substring(0, s.indexOf(";"));
// aCookie = hdrString.substring(0, s.indexOf(";"));
int j = aCookie.indexOf("=");
if (j != -1) {
if (!theCookies.containsKey(aCookie.substring(0, j))){
// if the Cookie do not already exist then when keep it,
// you may want to add some logic to update the stored Cookie instead.
// thanks to rwhelan
theCookies.put(aCookie.substring(0, j),aCookie.substring(j + 1));
if (printCookies){
System.println("Reading Key: " + aCookie.substring(0, j));
System.println(" Val: " + aCookie.substring(j + 1));
}
}
}
}
}
i++;
}
}
public void viewAllCookies() {
System.println("All Cookies are:");
Enumeration keys = theCookies.keys();
String key;
while (keys.hasMoreElements()){
key = (String)keys.nextElement();
System.println(" " + key + "=" +
theCookies.get(key));
}
}
public void viewURLCookies(URLConnection urlConn) {
System.out.print("Cookies in this URLConnection are:\n ");
System.println(urlConn.getRequestProperty("Cookie"));
}
public void addCookie(String _key, String _val, boolean printCookies){
if (!theCookies.containsKey(_key)){
theCookies.put(_key,_val);
if (printCookies){
System.println("Adding Cookie: ");
System.println(" " + _key + " = " + _val);
}
}
}
}
} |
Partager