[Java] CookieHandler 使用Demo →→→→→进入此内容的聊天室

来自 , 2020-08-02, 写在 Java, 查看 146 次.
URL http://www.code666.cn/view/a1d33d0d
  1. import java.io.IOException;
  2. import java.net.CookieHandler;
  3. import java.net.URI;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6. import java.text.DateFormat;
  7. import java.text.ParseException;
  8. import java.text.SimpleDateFormat;
  9. import java.util.Collections;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.LinkedList;
  13. import java.util.List;
  14. import java.util.Locale;
  15. import java.util.Map;
  16.  
  17. public class Fetch5 {
  18.     public static void main (String args[]) throws Exception {
  19.         String urlString = "java.sun.com";
  20.         CookieHandler.setDefault (new ListCookieHandler() );
  21.         URL url = new URL (urlString);
  22.         URLConnection connection = url.openConnection();
  23.         Object obj = connection.getContent();
  24.         url = new URL (urlString);
  25.         connection = url.openConnection();
  26.         obj = connection.getContent();
  27.     }
  28. }
  29.  
  30. class ListCookieHandler extends CookieHandler {
  31.     private List<Cookie> cookieJar = new LinkedList<Cookie>();
  32.  
  33.     public void put (URI uri, Map<String, List<String>> responseHeaders) throws IOException {
  34.         List<String> setCookieList = responseHeaders.get ("Set-Cookie");
  35.         if (setCookieList != null) {
  36. for (String item : setCookieList) {
  37.                 Cookie cookie = new Cookie (uri, item);
  38. for (Cookie existingCookie : cookieJar) {
  39.                     if ( (cookie.getURI().equals (existingCookie.getURI() ) )
  40.                     && (cookie.getName().equals (existingCookie.getName() ) ) ) {
  41.                         cookieJar.remove (existingCookie);
  42.                         break;
  43.                     }
  44.                 }
  45.                 cookieJar.add (cookie);
  46.             }
  47.         }
  48.     }
  49.  
  50.     public Map<String, List<String>> get (URI uri, Map<String, List<String>> requestHeaders)
  51.     throws IOException {
  52.         StringBuilder cookies = new StringBuilder();
  53. for (Cookie cookie : cookieJar) {
  54.             // Remove cookies that have expired
  55.             if (cookie.hasExpired() ) {
  56.                 cookieJar.remove (cookie);
  57.             } else if (cookie.matches (uri) ) {
  58.                 if (cookies.length() > 0) {
  59.                     cookies.append (", ");
  60.                 }
  61.                 cookies.append (cookie.toString() );
  62.             }
  63.         }
  64.  
  65.         Map<String, List<String>> cookieMap = new HashMap<String, List<String>> (requestHeaders);
  66.  
  67.         if (cookies.length() > 0) {
  68.             List<String> list = Collections.singletonList (cookies.toString() );
  69.             cookieMap.put ("Cookie", list);
  70.         }
  71.         System.out.println ("CookieMap: " + cookieMap);
  72.         return Collections.unmodifiableMap (cookieMap);
  73.     }
  74. }
  75.  
  76. class Cookie {
  77.  
  78.     String name;
  79.  
  80.     String value;
  81.  
  82.     URI uri;
  83.  
  84.     String domain;
  85.  
  86.     Date expires;
  87.  
  88.     String path;
  89.  
  90.     private static DateFormat expiresFormat1 = new SimpleDateFormat ("E, dd MMM yyyy k:m:s 'GMT'",
  91.             Locale.US);
  92.  
  93.     private static DateFormat expiresFormat2 = new SimpleDateFormat ("E, dd-MMM-yyyy k:m:s 'GMT'",
  94.             Locale.US);
  95.  
  96.     public Cookie (URI uri, String header) {
  97.         String attributes[] = header.split (";");
  98.         String nameValue = attributes[0].trim();
  99.         this.uri = uri;
  100.         this.name = nameValue.substring (0, nameValue.indexOf ('=') );
  101.         this.value = nameValue.substring (nameValue.indexOf ('=') + 1);
  102.         this.path = "/";
  103.         this.domain = uri.getHost();
  104.  
  105.         for (int i = 1; i < attributes.length; i++) {
  106.             nameValue = attributes[i].trim();
  107.             int equals = nameValue.indexOf ('=');
  108.             if (equals == -1) {
  109.                 continue;
  110.             }
  111.             String name = nameValue.substring (0, equals);
  112.             String value = nameValue.substring (equals + 1);
  113.             if (name.equalsIgnoreCase ("domain") ) {
  114.                 String uriDomain = uri.getHost();
  115.                 if (uriDomain.equals (value) ) {
  116.                     this.domain = value;
  117.                 } else {
  118.                     if (!value.startsWith (".") ) {
  119.                         value = "." + value;
  120.                     }
  121.                     uriDomain = uriDomain.substring (uriDomain.indexOf ('.') );
  122.                     if (!uriDomain.equals (value) ) {
  123.                         throw new IllegalArgumentException ("Trying to set foreign cookie");
  124.                     }
  125.                     this.domain = value;
  126.                 }
  127.             } else if (name.equalsIgnoreCase ("path") ) {
  128.                 this.path = value;
  129.             } else if (name.equalsIgnoreCase ("expires") ) {
  130.                 try {
  131.                     this.expires = expiresFormat1.parse (value);
  132.                 } catch (ParseException e) {
  133.                     try {
  134.                         this.expires = expiresFormat2.parse (value);
  135.                     } catch (ParseException e2) {
  136.                         throw new IllegalArgumentException ("Bad date format in header: " + value);
  137.                     }
  138.                 }
  139.             }
  140.         }
  141.     }
  142.  
  143.     public boolean hasExpired() {
  144.         if (expires == null) {
  145.             return false;
  146.         }
  147.         Date now = new Date();
  148.         return now.after (expires);
  149.     }
  150.  
  151.     public String getName() {
  152.         return name;
  153.     }
  154.  
  155.     public URI getURI() {
  156.         return uri;
  157.     }
  158.  
  159.     public boolean matches (URI uri) {
  160.  
  161.         if (hasExpired() ) {
  162.             return false;
  163.         }
  164.         String path = uri.getPath();
  165.         if (path == null) {
  166.             path = "/";
  167.         }
  168.  
  169.         return path.startsWith (this.path);
  170.     }
  171.  
  172.     public String toString() {
  173.         StringBuilder result = new StringBuilder (name);
  174.         result.append ("=");
  175.         result.append (value);
  176.         return result.toString();
  177.     }
  178. }
  179.  

回复 " CookieHandler 使用Demo"

这儿你可以回复上面这条便签

captcha