01 /**
02 * 本程序可以模拟web登录。向服务器端提交数据。
03 * 1、向服务器post多个参数时,如何做?
04 * 2、如何取得一个连接的Cookie和sessionId?
05 * 3、如何使用sessionId访问一个网站?
06 */
07
08 import java.io.BufferedReader;
09 import java.io.IOException;
10 import java.io.InputStreamReader;
11 import java.io.OutputStream;
12 import java.net.HttpURLConnection;
13 import java.net.URL;
14
15
16 public class TestLoginWeb {
17
18 public static void main(String args[]) throws IOException {
19
20 URL url = new URL("http://localhost:8080/backgroundH/login.jsp");
21 URL url1 = new URL("http://localhost:8080/backgroundH/execute.jsp");
22 HttpURLConnection huc = (HttpURLConnection) url.openConnection();
23
24 // 设置允许output
25 huc.setDoOutput(true);
26 // 设置为post方式
27 huc.setRequestMethod("POST");
28 huc.setRequestProperty("user-agent", "mozilla/4.7 [en] (win98; i)");
29
30 OutputStream os = huc.getOutputStream();
31 // 多个参数的输出时,需要用&连接,并转换成bytes
32 os.write("name=gaolei".getBytes("gbk"));
33 os.close();
34
35 BufferedReader br = new BufferedReader(
36 new InputStreamReader(huc.getInputStream()));
37
38 huc.connect();
39 String line = br.readLine();
40
41 while (line != null) {
42 System.out.println(line);
43 line = br.readLine();
44 }
45
46 // 取得cookie
47 String cookieval = huc.getHeaderField("set-cookie");
48
49 System.out.println(cookieval);
50 String sessionid = null;
51
52 // 取得cookie,这段代码对于不同网站不同,因为有的网站有多个session标识
53 if (cookieval != null) {
54 sessionid = cookieval.substring(0, cookieval.indexOf(";"));
55 }
56
57 huc.disconnect();
58 huc = null;
59
60 HttpURLConnection huc1 = (HttpURLConnection) url1.openConnection();
61 // 使用sessionId访问一个网站
62 huc1.setRequestProperty("cookie", sessionid);
63 // 设置允许output
64 huc1.setDoOutput(true);
65 // 设置为post方式
66 huc1.setRequestMethod("POST");
67 huc1.setRequestProperty("user-agent", "mozilla/4.7 [en] (win98; i)");
68
69 OutputStream os1 = huc1.getOutputStream();
70
71 os1.write("value=1234567890".getBytes("gbk"));
72 os1.close();
73
74 BufferedReader br1 = new BufferedReader(
75 new InputStreamReader(huc1.getInputStream()));
76
77 huc1.connect();
78 line = br1.readLine();
79 while (line != null) {
80 System.out.println(line);
81 line = br1.readLine();
82 }
83 huc1.disconnect();
84
85 }
86 }
87
第31行,关于POST多个参数到服务器端,可以参照下面代码:
StringBuffer params = new StringBuffer("typeid=");
params.append(args[0]).append("&");
params.append("keyword=").append(args[1]);
os.write(params.toString().getBytes("gb2312"));