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

Geo*_*Geo 19 java header 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();
Run Code Online (Sandbox Code Playgroud)

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

Ken*_*tle 21

必须在获取InputStream任何影响之前设置标头- IllegalStateException如果连接已打开,则将抛出标头.

至于User-Agent标题具体,如果已经设置它应该被发送.

请参阅URLConnection JavaDoc.