在 URLConnection 中设置标头的正确方法是什么?
我的代码如下:
URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();
如果我在获取InputStream
之前设置标头可以吗? 我的标头是否会被发送,或者服务器是否会看到默认的 URLConnection
的用户代理(如果有)?
My code is like the following:
URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();
Is it ok if I set the headers before I get the InputStream
? Will my header be sent, or will the server see the default URLConnection
's user-agent ( if any ) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在使
InputStream
产生任何影响之前,必须设置标头 - 如果连接已打开,则会抛出IllegalStateException
。具体就
User-Agent
标头而言,如果已设置,则应发送该标头。请参阅 URLConnection JavaDoc。
The headers must be set prior to getting the
InputStream
to have any affect - anIllegalStateException
will be thrown if the connection is already open.As far as the
User-Agent
header specifically, it should be sent if it has been set.See the URLConnection JavaDoc.
要回答这个问题,代码是正确的。 当 getInputStream() 时,HTTP get 被发送到目标服务器。
关于用户代理的旁注,如果您不设置它,URLConnection 无论如何都会发送默认的,即:
To answer the question, the code is correct. The moment getInputStream(), an HTTP get is sent to the target server.
A side-note on user-agent, if you don't set it, URLConnection will send the default one anyway, which is:
我建议不要使用低级构造,例如 URLConnection。 有很多用于发送 HTTP 请求的库,其中最著名的是 Apache HTTP Client。
I'd advise against using low-level constructs such as URLConnection. There are plenty of libraries for sending HTTP requests, with the most prominent being Apache HTTP Client.