问题描述
URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
是
connection.setRequestProperty(key, value);
与
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("key=" + value);
writer.close();
?
如果没有,请更正我。
推荐答案
不,不是。 URLConnection #setRequestProperty()
设置请求标题。对于HTTP请求,您可以在找到所有可能的标题。
No, it is not. The URLConnection#setRequestProperty()
sets a request header. For HTTP requests you can find all possible headers here.
作家
只需写入请求正文。对于带有urlencoded内容的 POST
,您通常会将查询字符串写入请求正文,而不是将其附加到请求URI,如中所示GET
。
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
.
那就是说, connection.setDoOutput(true);
已经隐式设置在HTTP URI的情况下, POST
的请求方法(因为它隐含地需要写入请求主体),所以做一个 connection.setRequestMethod (POST);之后
是不必要的。
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.
这篇关于connection.setRequestProperty和明确写入urloutputstream是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!