問題描述
我的代碼如下:
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
之前設(shè)置標(biāo)頭可以嗎?我的標(biāo)頭會(huì)被發(fā)送,還是服務(wù)器會(huì)看到默認(rèn)的 URLConnection
的用戶代理(如果有)?
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
之前必須設(shè)置標(biāo)頭 以產(chǎn)生任何影響 - 如果連接已經(jīng)打開,將拋出 IllegalStateException
.
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.
具體到 User-Agent
標(biāo)頭,如果已設(shè)置則應(yīng)發(fā)送.
As far as the User-Agent
header specifically, it should be sent if it has been set.
請參閱 URLConnection JavaDoc.
See the URLConnection JavaDoc.
這篇關(guān)于在 URLConnection 中設(shè)置標(biāo)頭的正確方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!