title: Read session variable using HttpURLConnection
body: <p>I am trying to log in to a website using an <strong>HttpURLConnection</strong>. </p>
  
  <p>If the login is successful, the server sets <code>user_id</code> variable in the current session. </p>
  
  <p>Using SO and the <a href="http://developer.android.com/training/basics/network-ops/connecting.html#download" rel="nofollow">Google developer docs</a> 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? </p>
  
  <p>For reference here is my code:</p>
  
  <pre><code>String body = "user=chris&amp;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());
  </code></pre>
  
  <p><em>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.</em> 
  <s></p>
  
  <h2>Update</h2>
  
  <p>Okay, apparently my body is not getting submitted after all. When I do a <code>console.log(util.inspect(req.body))</code> in my server code, it prints <code>{}</code>. I double-checked the request method and that is POST. What am I doing wrong? 
  </s></p>
  
  <p><em>Rewrote the code, and even though I think I did the exact same thing as before it's working now. Weird, but whatever.</em></p>