URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
Is
connection.setRequestProperty(key, value);
the same as
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("key=" + value);
writer.close();
?
If not, please correct me.
No, it is not. The
URLConnection#setRequestProperty()sets a request header. For HTTP requests you can find all possible headers here.The
writerjust writes the request body. In case ofPOSTwith urlencoded content, you’d normally write the query string into the request body instead of appending it to the request URI like as inGET.That said,
connection.setDoOutput(true);already implicitly sets the request method toPOSTin case of a HTTP URI (because it’s implicitly required to write to the request body then), so doing anconnection.setRequestMethod("POST");afterwards is unnecessary.