Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection.setRequestProperty and excplicitly writing to the urloutputstream are they same?

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.

like image 303
Bunny Rabbit Avatar asked Feb 03 '23 05:02

Bunny Rabbit


1 Answers

No, it is not. The URLConnection#setRequestProperty() sets a request header. For HTTP requests you can find all possible headers here.

The writer just writes the request body. In case of POST with urlencoded content, you'd normally write the query string into the request body instead of appending it to the request URI like as in GET.

That said, connection.setDoOutput(true); already implicitly sets the request method to POST in case of a HTTP URI (because it's implicitly required to write to the request body then), so doing an connection.setRequestMethod("POST"); afterwards is unnecessary.

like image 156
BalusC Avatar answered Feb 05 '23 19:02

BalusC