1. [代码]WebClient.java
01import java.io.BufferedReader;
02import java.io.InputStream;
03import java.io.InputStreamReader;
04import java.net.CookieHandler;
05import java.net.CookieManager;
06import java.net.CookiePolicy;
07import java.net.CookieStore;
08import java.net.HttpCookie;
09import java.net.URI;
10import java.net.URL;
11import java.net.URLConnection;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.HashMap;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18
19
20public class WebClient {
21 public static void main(String[] args) throws Exception {
22 CookieStore store = new MyCookieStore();
23 CookiePolicy policy = new MyCookiePolicy();
24 CookieManager handler = new CookieManager(store, policy);
25 CookieHandler.setDefault(handler);
26 URL url = new URL("http://localhost:8080/cookieTest.jsp");
27 URLConnection conn = url.openConnection();
28
29 InputStream in = conn.getInputStream();
30 BufferedReader reader = new BufferedReader(new InputStreamReader(in));
31 String input;
32 while ((input = reader.readLine()) != null) {
33 System.out.println(input);
34 }
35 reader.close();
36
37 }
38}
39
40class MyCookiePolicy implements CookiePolicy {
41 public boolean shouldAccept(URI uri, HttpCookie cookie) {
42// String host = uri.getHost();
43 // return host.equals("localhost");
44 return true;
45 }
46}
47
48class MyCookieStore implements CookieStore {
49 private Map<URI, List<HttpCookie>> map = new HashMap<URI, List<HttpCookie>>();
50
51 public void add(URI uri, HttpCookie cookie) {
52 List<HttpCookie> cookies = map.get(uri);
53 if (cookies == null) {
54 cookies = new ArrayList<HttpCookie>();
55 map.put(uri, cookies);
56 }
57 cookies.add(cookie);
58 }
59
60 public List<HttpCookie> get(URI uri) {
61 List<HttpCookie> cookies = map.get(uri);
62 if (cookies == null) {
63 cookies = new ArrayList<HttpCookie>();
64 map.put(uri, cookies);
65 }http://www.huiyi8.com/jiaoben/
66 return cookies;
67 }
68
69 public List<HttpCookie> getCookies() {
70 Collection<List<HttpCookie>> values = map.values();
71 List<HttpCookie> result = new ArrayList<HttpCookie>();
72 for (List<HttpCookie> value : values) {
73 result.addAll(value);
74 }
75 return result;
76 }
77
78 public List<URI> getURIs() {
79 Set<URI> keys = map.keySet();
80 return new ArrayList<URI>(keys);
81
82 }
83
84 public boolean remove(URI uri, HttpCookie cookie) {
85 List<HttpCookie> cookies = map.get(uri);
86 if (cookies == null) {
87 return false;
88 }
89 return cookies.remove(cookie);
90 }
91
92 public boolean removeAll() {
93 map.clear();
94 return true;
95 }
96}