java.net.URL 模拟用户登录网页并维持session【转】

时间:2023-03-09 16:22:12
java.net.URL 模拟用户登录网页并维持session【转】

java.net.URL 模拟用户登录网页并维持session

半成品,并非完全有用

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class SessionHolder {
public static void main(String[] args) throws Exception {
URL url = new URL("http://192.168.1.147:144/platformproxy/j_spring_security_check");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 允许连接提交信息
connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST”
connection.setRequestProperty("User-Agent", "Mozilla/4.7 [en] (Win98; I)");
StringBuffer sb = new StringBuffer();
// sb.append("username=admin");
// sb.append("&password=admin");
sb.append("j_username=09000001");
sb.append("&j_password=zsinsgooda");
OutputStream os = connection.getOutputStream();
os.write(sb.toString().getBytes());
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseCookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie
System.out.println("cookie:" + responseCookie);
String line = br.readLine();
while (line != null) {
System.out.println(new String(line.getBytes()));
line = br.readLine();// 打出登录的网页
}
// acces
URL url1 = new URL("网页的登录后的页面");
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestProperty("Cookie", responseCookie);// 给服务器送登录后的cookie
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
String line1 = br1.readLine();
while (line1 != null) {
System.out.println(new String(line1.getBytes()));
line1 = br1.readLine();
}
}
}

引用自:http://blog.csdn.net/zgrjkflmkyc/article/details/9150511