title: HttpURLConnection POST request - cannot send data to server
body: <p>I have this code:</p>
  
  <pre><code>HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setReadTimeout(10000);
  conn.setConnectTimeout(10000);
  conn.setRequestMethod(type);
  conn.setDoOutput(output);
  if(output)
     conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  conn.setDoInput(true);
  
  conn.connect();
  
  OutputStream out = null;
  if(output)
     out = conn.getOutputStream();
  InputStream in = conn.getInputStream();
  
  if(output) {
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
      bw.write(getQuery(params));
      bw.flush();
  }
  
  // Get output
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  StringBuilder sb = new StringBuilder();
  String line;
  while((line = br.readLine()) != null) {
      sb.append(line);
      sb.append("\n");
  }
  
  in.close();
  if(output)
      out.close();
  
  // Do stuff with the output
  </code></pre>
  
  <p>This code throws an IOException when <code>output</code> is true (doing a POST or PUT request), and doesn't complete the request. I've tried reordering the <code>conn.connect()</code>, write call, and stream creation blocks, but no permutation worked.</p>
  
  <p>In all cases, the BufferedReader works just fine and doesn't throw any exceptions. <code>getQuery</code> correctly returns a URL-encoded string.</p>
  
  <p>Here's the stack trace from the IOException:</p>
  
  <pre><code>java.io.IOException: closed
  W/System.err﹕ at com.android.okio.RealBufferedSink$1.write(RealBufferedSink.java:129)
  W/System.err﹕ at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
  W/System.err﹕ at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:158)
  W/System.err﹕ at java.io.BufferedWriter.flush(BufferedWriter.java:124)
  W/System.err﹕ at org.project.NetworkHelper.doRequest(NetworkHelper.java:57)
  W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
  </code></pre>
  
  <p>What ends up happening is that the request goes through, but none of the POST or PUT data ends up at the server - it's like the write call never happened.</p>
  
  <p>Does anyone have any idea what could cause this, or how to fix it?</p>