Java模拟网站登录

 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 }

 

posted @ 2014-03-04 23:12  dekevin  阅读(1498)  评论(0编辑  收藏  举报