在Android项目中使用到了HttpURLConnection请求资源,对于其中的方法setRequestProperty()的调用顺序有些疑惑。
API注释如下所示:
即:这个方法只能够在连接建立之前调用。
也就是说,该方法只能在连接建立之前调用才能使得设置的相应参数生效。
我的问题是:如果调用了setRequestProperty(name,value)之后没有明确调用connect()方法,那设置的参数是否会生效呢?
第一直觉是如果调用了setRequestProperty(name,value)之后没有明确调用connect()方法,那么设置的对应参数是不会生效的!
为了验证我的想法,做了如下验证:
实验一:在调用setRequestProperty(name,value)之后,调用getInputStream()之前没有明确调用connect()方法,代码如下所示:
String resource = "http://www.blogjava.net/supercrsky/articles/247449.html";
URL url = new URL(resource);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
//conn.connect();
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int count = -1;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((count = is.read(buffer)) > 0) {
bos.write(buffer, 0, count);
}
buffer = bos.toByteArray();
System.out.println(new String(buffer,"UTF-8"));
conn.disconnect();
运行程序,抓包结果:
GET /supercrsky/articles/247449.html HTTP/1.1
Content-Type: text/plain; charset=utf-8 // 显然,设置的属性生效了!
User-Agent: Java/1.6.0_21
Host: www.blogjava.net
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
实验二:在调用setRequestProperty(name,value)之后,调用getInputStream()之前明确调用connect()方法,代码如下所示:
String resource = "http://www.blogjava.net/supercrsky/articles/247449.html";
URL url = new URL(resource);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
conn.connect();
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int count = -1;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((count = is.read(buffer)) > 0) {
bos.write(buffer, 0, count);
}
buffer = bos.toByteArray();
System.out.println(new String(buffer,"UTF-8"));
conn.disconnect();
运行程序,抓包结果:
GET /supercrsky/articles/247449.html HTTP/1.1
Content-Type: text/plain; charset=utf-8 // 显然,设置的属性也生效了!
User-Agent: Java/1.6.0_21
Host: www.blogjava.net
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
结论:
1. 很显然,不论是否明确调用connect()方法,通过setRequestProperty(name,value)设置的属性都生效了,那这是为什么呢?
经过一番查证,原来是在调用getInputStream()方法中会检查连接是否已经建立,如果没有建立,则会调用connect()方法,所以疑惑解开了!
原来是在调用getInputStream()的时候会做连接是否建立的检查!
2. 那么,在写代码的时候是否需要明确调用connect()呢?
个人建议还是明确调用一些比较好,因为这样对于程序员自己来说是一个明确的控制,否则埋藏一些隐性的BUG,难以察觉。
相关资料:
(1)参考:http://www.blogjava.net/supercrsky/articles/247449.html
(2)HttpURLConnection源码:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/net/www/protocol/http/HttpURLConnection.java#HttpURLConnection.plainConnect%28%29