简体   繁体   English

使用HttpURLConnection读取会话变量

[英]Read session variable using HttpURLConnection

I am trying to log in to a website using an HttpURLConnection . 我正在尝试使用HttpURLConnection登录到网站。

If the login is successful, the server sets user_id variable in the current session. 如果登录成功,则服务器在当前会话中设置user_id变量。

Using SO and the Google developer docs on the matter I have been able to POST my credentials to the server, but how do I get the user_id from the session now? 通过使用SO和Google开发人员文档 ,我已经可以将我的凭据发布到服务器上,但是现在如何从会话中获取user_id?

For reference here is my code: 供参考的是我的代码:

String body = "user=chris&password=geheim";
HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setInstanceFollowRedirects(false);

conn.connect();
OutputStream out = conn.getOutputStream();
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

out.write(body.getBytes());
int response = conn.getResponseCode();
String s = "";
for (int c = in.read(); c != -1; c = in.read()) {
    s += (char) c;
}
System.out.println(response);
System.out.println(s);
System.out.println(conn.getHeaderFields());

Note: to make it easier to read I've left out all exception handling and resource management. 注意:为了便于阅读,我省略了所有异常处理和资源管理。 Also this is just trial code connecting to my localhost, so no worries about the hardcoded credentials and other insecurities. 而且,这只是连接到我的本地主机的试用代码,因此不必担心硬编码的凭据和其他不安全因素。

Update 更新

Okay, apparently my body is not getting submitted after all. 好吧,显然我的身体毕竟没有屈服。 When I do a console.log(util.inspect(req.body)) in my server code, it prints {} . 当我在服务器代码中执行console.log(util.inspect(req.body))时,它将输出{} I double-checked the request method and that is POST. 我仔细检查了请求方法,那就是POST。 What am I doing wrong? 我究竟做错了什么?

Rewrote the code, and even though I think I did the exact same thing as before it's working now. 重新编写了代码,即使我认为我所做的工作与之前一样完全相同,现在也可以正常工作。 Weird, but whatever. 很奇怪,但是随便吧。

The session where the user_id is stored, is kept on the server. 存储user_id的会话保留在服务器上。 All the client usually gets is a session-id in a session cookie (eg JSESSIONID) that is passed back to the server so the server can find the correct session and data again. 客户端通常获得的只是会话cookie中的会话ID(例如JSESSIONID),该ID会传递回服务器,以便服务器可以再次找到正确的会话和数据。

That's why you also can put large amounts of data into a user's session ... imagine all of that was actually passed to the client! 这就是为什么您还可以将大量数据放入用户会话中的原因……想象所有这些数据实际上已传递给客户端!

您不能,除非服务器中有一个合作的活动页面可以将其提供给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM