用java寫的一個模擬登錄程序,轉到userInfo 頁面時卻得不到用戶信息,懷疑是得不到session。
貼上代碼,像這樣先取得cookie 再發回去的方法好像不可行?
public static void login() throws HttpException, IOException{
URL url = new URL("http://localhost/ONCAPS/login.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);//允許連接提交信息
connection.setRequestMethod("POST");//網頁提交方式“GET”、“POST”
connection.setRequestProperty("User-Agent", "Mozilla/4.7 en");
StringBuffer sb = new StringBuffer();
sb.append("user_id=test1");
sb.append("password=123456");
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("http://localhost/ONCAPS/userInfo.php");
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();
}
}
謝謝各位
得到服務器的session,並且之後的訪問帶上cookie