質問

I am trying to log in to a website using an HttpURLConnection.

If the login is successful, the server sets user_id variable in the current session.

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?

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 {}. I double-checked the request method and that is 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. All the client usually gets is a session-id in a session cookie (e.g. JSESSIONID) that is passed back to the server so the server can find the correct session and data again.

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!

他のヒント

You can't, unless there is a co-operative active page in the server that will give it to you.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top