2013-04-20 68 views
24

我在URLConnection類中有一個難以理解connect()方法的含義。在下面的代碼中,如果我使用connect()方法,如果我不使用它,我會得到相同的結果。Java URLConnection - 什麼時候需要使用connect()方法?

爲什麼(或何時)需要使用它?

URL u = new URL("http://example.com"); 
HttpURLConnection conn = (HttpURLConnection) u.openConnection(); 

conn.connect();//with or without it I have the same result 

InputStream in = conn.getInputStream(); 
int b; 
while ((b = in.read()) != -1) { 
System.out.write(b); 
} 

回答

25

您並不總是需要顯式調用connect方法來啓動連接。

依賴於連接的操作(如getInputStream,getOutputStream等)將在必要時隱式執行連接。

這裏是甲骨文的文檔link

22
HttpURLConnection conn = (HttpURLConnection) u.openConnection(); 

只創建一個對象

connect()方法由conn.getInputStream();

+2

完全正確的調用。 Downvoter請解釋。 +1 – EJP 2014-05-14 01:16:00

相關問題