Android POST Message Doesn't get Sent
I've encountered a rather strange error. I've written an android application that uploads an simple text file to a server. The code for the connection is as follows:
try {
URL = new URL(myURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+"---");
DataOutputStream output = new DataOutPutstream(connection.ge开发者_运维问答tOutputStream());
output.writeBytes(<my post request>);
output.flush();
output.close();
connection.connect();
}
When I run this method, the post request is never sent over to the server. Nothing shows up on wireshark and if I look in logcat, there are no errors and the connection gets made fine, the POST message is just never sent. However, if I add a simple line right after the connection.connect() such as:
connection.getResponseCode();
Suddenly the POST message gets sent over no problem. What's going on here? Am I required to get a response code in order for the message to get sent over?
- Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream? In short you must call getInputStream() and close it. getResponseCode() is also working because it requires an established connection.
You do not need to call
connection.connect(); which is redundant.
You can get working sample from here: http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
You set doInput to true. Maybe the url connection waits for an input because of that. Try to set it to false. But I could also be wrong. It is just a guess.
精彩评论