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.