JavaシミュレーションWebサイトへのログイン

9113 ワード

 1 web          ,cookie    ,post get     。
 2 
 3 1.       java.io.InputStream   in;
 4 java.net.URL url = new java.net.URL(www.xyz.com/content.html);
 5 java.net.HttpURLConnection connection = (java.net.HttpURLConnection)
 6 url.openConnection();
 7 connection = (java.net.HttpURLConnection) url.openConnection();
 8 //   IE
 9 connection.setRequestProperty(“User-Agent”,”Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)”);
10 connection.connect();
11 in = connection.getInputStream();
12 java.io.BufferedReader breader =
13 new BufferedReader(new InputStreamReader(in , “GBK”));
14 String str=breader.readLine());
15 while(st != null){
16 System.out.println(str); str=breader.readLine());
17 }
18 2.cookie  
19 1.     
20   cookie:
21 HttpURLConnection huc= (HttpURLConnection) url.openConnection();
22 InputStream is = huc.getInputStream();
23 //   sessionID.
24 String cookieVal = hc.getHeaderField(“Set-Cookie”);
25 String sessionId;
26 if(cookieVal != null)
27 {
28 sessionId = cookieVal.substring(0, cookieVal.indexOf(“;”));
29 }
30     cookie:
31 HttpURLConnection huc= (HttpURLConnection) url.openConnection();
32 if(sessionId != null)
33 {
34 huc.setRequestProperty(“Cookie”, sessionId);
35 }
36 InputStream is = huc.getInputStream();
37 
38 2.   jcookie (http://jcookie.sourceforge.net/ )
39   cookie:
40 URL url = new URL(“http://www.site.com/”);
41 HttpURLConnection huc = (HttpURLConnection) url.openConnection();
42 huc.connect();
43 InputStream is = huc.getInputStream();
44 Client client = new Client();
45 CookieJar cj = client.getCookies(huc);
46 
47     ,       cookie:
48 url = new URL(“http://www.site.com/”);
49 huc = (HttpURLConnection) url.openConnection();
50 client.setCookies(huc, cj);
51 
52 3.post     
53 URL url = new URL(“www.xyz.com”);
54 HttpURLConnection huc = (HttpURLConnection) url.openConnection();
55 //    output
56 huc.setDoOutput(true);
57 //   post  
58 huc.setRequestMethod(“POST”);
59 huc.setRequestProperty(“User-Agent”,”Mozilla/4.7 [en] (Win98; I)”);
60 StringBuffer sb = new StringBuffer();
61 sb.append(“userName=”+userNme);
62 sb.append(“&password=”+password);
63 
64 //post  
65 OutputStream os = huc.getOutputStream();
66 os.write(sb.toString().getBytes(“GBK”));
67 os.close();
68 
69 BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream()))
70 huc.connect();
71 String line = br.readLine();
72 while(line != null){
73 System.out.printli(line);
74 line = br.readLine();
75 }