java connection.setRequestProperty 和明确写入 urloutputstream 是否相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2560150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
connection.setRequestProperty and excplicitly writing to the urloutputstream are they same?
提问by Bunny Rabbit
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.
如果没有,请纠正我。
回答by BalusC
No, it is not. The URLConnection#setRequestProperty()sets a request header. For HTTP requests you can find all possible headers here.
不它不是。的URLConnection#setRequestProperty()设置的请求报头。对于 HTTP 请求,您可以在此处找到所有可能的标头。
The writerjust writes the request body. In case of POSTwith 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.
在writer刚刚写入请求体。在POST使用 urlencoded 内容的情况下,您通常会将查询字符串写入请求正文中,而不是像GET.
That said, connection.setDoOutput(true);already implicitly sets the request method to POSTin 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.
也就是说,在 HTTP URI 的情况下,connection.setDoOutput(true);已经隐式设置了请求方法POST(因为它隐式要求写入请求正文),因此connection.setRequestMethod("POST");之后进行是不必要的。

