connection.setRequestProperty和明确写入urloutputstream是一样的吗? [英] connection.setRequestProperty and excplicitly writing to the urloutputstream are they same?

查看:130
本文介绍了connection.setRequestProperty和明确写入urloutputstream是一样的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆