模拟登录中,如何保持session

梁不正 2015-10-04 12:13:10
用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();


}
}
谢谢各位
...全文
177 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
土豆你个番茄 2015-10-10
  • 打赏
  • 举报
回复
登陆后你把用户信息添加到session中了吗?我怎么没看到你的代码?
telake 2015-10-09
  • 打赏
  • 举报
回复
在cookie中取到SESSIONID,请求url的时候将SESSIONID放在cookie中

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧