1 package net.javacoding.jspider.core.util.http; 2 3 4 import net.javacoding.jspider.api.model.Cookie; 5 6 import java.net.URLConnection ; 7 import java.util.ArrayList ; 8 import java.util.StringTokenizer ; 9 10 11 17 public class CookieUtil { 18 19 public static final String HEADER_SET_COOKIE = "Set-Cookie"; 20 21 public Cookie[] getCookies(URLConnection connection) { 22 23 String [] cookieStrings = getCookieStrings(connection); 24 return getCookies(cookieStrings); 25 } 26 27 protected String [] getCookieStrings(URLConnection connection) { 28 ArrayList arrayList = new ArrayList (); 29 30 String headerKey = null; 31 String headerValue = null; 32 33 int i = 0; 34 35 do { 36 37 headerKey = connection.getHeaderFieldKey(i); 38 headerValue = connection.getHeaderField(i); 40 41 if (HEADER_SET_COOKIE.equalsIgnoreCase(headerKey)) { 42 if (headerValue != null) { 43 arrayList.add(headerValue.trim()); 44 } else { 45 arrayList.add(headerValue); 46 } 47 } 48 i++; 49 50 } while (headerKey != null || headerValue != null); 51 52 return (String []) arrayList.toArray(new String [arrayList.size()]); 53 } 54 55 protected Cookie[] getCookies(String [] cookieString) { 56 Cookie[] cookies = new Cookie[cookieString.length]; 57 int used = 0; 58 59 for (int i = 0; i < cookieString.length; i++) { 60 String s = cookieString[i]; 61 Cookie cookie = getCookie(s); 62 if (cookie != null) { 63 cookies[used++] = cookie; 64 } 65 } 66 Cookie[] retVal = new Cookie[used]; 67 System.arraycopy(cookies, 0, retVal, 0, used); 68 return retVal; 69 } 70 71 public Cookie getCookie(String cookieString) { 72 Cookie cookie = null; 73 if (cookieString != null && !cookieString.trim().equals("")) { 74 StringTokenizer st = new StringTokenizer (cookieString, ";"); 75 76 String name = ""; 77 String value = ""; 78 String domain = ""; 79 String path = ""; 80 String expires = ""; 81 82 while (st.hasMoreTokens()) { 84 String token = st.nextToken(); 85 StringTokenizer st2 = new StringTokenizer (token, "="); 86 if (st2.hasMoreTokens()) { 87 String propName = st2.nextToken().trim(); 88 if (st2.hasMoreTokens()) { 89 String propValue = st2.nextToken().trim(); 90 if ("value".equalsIgnoreCase(propName)) { 91 value = propValue; 92 } else if ("domain".equalsIgnoreCase(propName)) { 93 domain = propValue; 94 } else if ("path".equalsIgnoreCase(propName)) { 95 path = propValue; 96 } else if ("expires".equalsIgnoreCase(propName)) { 97 expires = propValue; 98 } else { 99 name = propName; 100 value = propValue; 101 } 102 } 103 } 104 } 105 cookie = new Cookie(name, value, domain, path, expires); 106 } 107 return cookie; 108 } 109 110 } 111 | Popular Tags |