I have this 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 This code throws an IOException when output is true (doing a POST or PUT request), and doesn't complete the request. I've tried reordering the conn.connect(), write call, and stream creation blocks, but no permutation worked.
In all cases, the BufferedReader works just fine and doesn't throw any exceptions. getQuery correctly returns a URL-encoded string.
Here's the stack trace from the IOException:
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) 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.
Does anyone have any idea what could cause this, or how to fix it?