Java 在 URLConnection 中设置标题的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/331538/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:32:02  来源:igfitidea点击:

What is the proper way of setting headers in a URLConnection?

javaheaderurlconnection

提问by Geo

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 ) ?

如果我在获取之前设置标题可以InputStream吗?我的标头会被发送,还是服务器会看到默认URLConnection的用户代理(如果有)?

采纳答案by Ken Gentle

The headers mustbe set prior to getting the InputStreamto have any affect - an IllegalStateExceptionwill be thrown if the connection is already open.

必须在获得InputStream任何影响之前设置标头-IllegalStateException如果连接已经打开,则会抛出an 。

As far as the User-Agentheader specifically, it should be sent if it has been set.

至于User-Agent具体的头部,如果已经设置就应该发送。

See the URLConnectionJavaDoc.

请参阅URLConnectionJavaDoc。

回答by Leif Ashley

To answer the question, the code is correct. The moment getInputStream(), an HTTP get is sent to the target server.

要回答这个问题,代码是正确的。在 getInputStream() 的那一刻,一个 HTTP get 被发送到目标服务器。

A side-note on user-agent, if you don't set it, URLConnection will send the default one anyway, which is:

关于用户代理的旁注,如果您不设置它,URLConnection 无论如何都会发送默认的,即:

User-Agent: Java/1.6.0_24 (varies depending on your java version)

回答by NewlessClubie

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.

我建议不要使用低级结构,例如 URLConnection。有很多用于发送 HTTP 请求的库,其中最突出的是 Apache HTTP Client。