梁不正 2015-10-03 14:40 采纳率: 18.2%
浏览 3999
已采纳

模拟登录中,如何保持session

用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();  


    }  
}

谢谢各位

  • 写回答

2条回答 默认 最新

  • devmiao 2015-10-03 15:58
    关注

    得到服务器的session,并且之后的访问带上cookie

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块
  • ¥15 nhanes加权logistic回归,svyglm函数