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

∥☆過路亽.° 提交于 2019-11-28 09:44:36
Ken Gentle

The headers must be set prior to getting the InputStream to have any affect - an IllegalStateException 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.

Leif Ashley

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:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!