title: HttpUrlConnection POST not working as expected
body: <p>I'm new to writing network code, and not very familiar with Java programming.</p>
  
  <p>I'm trying to write a snippet to log into a website. I need to use http POST to submit the username and password. </p>
  
  <p>I wrote a version using Apache http components and it worked fine, I could see there was a HTTP POST when monitoring the connection using Wireshark.</p>
  
  <pre><code>StringEntity loginForm = new StringEntity(postData);
  HttpPost loginPost = new HttpPost(LOG_IN_URL);
  loginPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
  loginPost.setEntity(loginForm);
  client.execute(loginPost);
  </code></pre>
  
  <p><em>The version above worked.</em></p>
  
  <p>The <code>postData</code> is </p>
  
  <pre><code>private static String getPostData(String checkCode) {
      String postinfo1 = "operation=&amp;usercode_text=myusername&amp;userpwd_text=password&amp;checkcode_text=";
      String postinfo2 = "&amp;submittype=%C8%B7+%C8%CF";
      String postData = postinfo1 + checkCode + postinfo2;
      return postData;
  }
  </code></pre>
  
  <p>Then I wrote another one using HttpUrlConnection</p>
  
  <pre><code>URL logInUrl = new URL(LOG_IN_URL);
  HttpURLConnection logConn = (HttpURLConnection) logInUrl.openConnection();
  logConn.setDoOutput(true);
  logConn.setRequestMethod("POST");
  logConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  logConn.setChunkedStreamingMode(0);
  OutputStream out = logConn.getOutputStream();
  BufferedWriter logPost = new BufferedWriter(new OutputStreamWriter(out));
  logPost.print(postData);
  logPost.close();
  </code></pre>
  
  <p>After this block is executed, I can only see some TCP packages on Wireshark, but not a HTTP POST after them (as in the case with the Apache http components version), and I cannot log in to the website.</p>
  
  <p><em>I am curious about the possible difference in the two versions of code the cause the latter to fail.</em></p>
  
  <p><strong>UPDATE</strong>
  I don't know why. But after I added </p>
  
  <pre><code>logConn.getResponseCode();
  </code></pre>
  
  <p>It works now. (Deleting this line it will fail). Can anyone explain why?</p>