I've 'fixed' this but I don't understand why my fix works and that bothers me. The code below is supposed to an HTTP POST to a remote server. I have two lines commented out. With the two lines commented out, it appears to write to the HTTP connection it has opened, but nothing is received on the remote server. There are no errors and no exceptions. With the two lines uncommented, requesting a response HTTP code, the data appears to be actually sent. Why? I wrote this originally without the two lines, assuming that a flush and a close of the connection would behave in the same manner as flushing and closing a file connection: what is in the buffer gets written. But this appears not to be the case. Is there a better way to flush and send the POST data than what I am doing?
private void post()
throws IOException {
System.out.println("Posting xml to url " + postUrl);
byte[] postData = htmlOutput.getBytes();
URL post = new URL(postUrl);
HttpURLConnection conn = (HttpURLConnection) post.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
conn.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
conn.disconnect();
// int responseCode = conn.getResponseCode();
// System.out.println("POST Response Code from server was " + responseCode);
System.out.println("Finished posting xml to url " + postUrl);
}