2013-08-06 198 views
0

我很好奇HttpURLConnection如何獲取連接的輸入流。我查了父抽象類URLConnection的實施,發現該方法HttpURLConnection如何獲得它的inputStream實例?

/** 
    * Returns an {@code InputStream} for reading data from the resource pointed by 
    * this {@code URLConnection}. It throws an UnknownServiceException by 
    * default. This method must be overridden by its subclasses. 
    * 
    * @return the InputStream to read data from. 
    * @throws IOException 
    *    if no InputStream could be created. 
    */ 
    public InputStream getInputStream() throws IOException { 
     throw new UnknownServiceException("Does not support writing to the input stream"); 
    } 
  1. HttpURLConnection的延伸URLConnection的犯規重寫此方法。所以想知道如何獲得輸入流參考?

  2. 與此有關的東西....什麼時候http請求轉到客戶端到服務器?當你調用getInputStream()嗎?或只要openConnection()被調用?

在此先感謝 AK

回答

3

如果打印HttpURLConnection對象的運行時類型將是org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl類型的Android上。這就是您執行getInputStream()的地方。

僅供參考,如果你要打印在Oracle JRE同一個對象的運行時類型,運行時類型將是sun.net.www.protocol.http.HttpURLConnection

注: 我首先列出了Android版本,因爲這個問題以前被標記爲一個Android問題。

+0

謝謝開發。我正在使用java.net.HttpURLConnection,正如你所說的它的sun.net.www.protocol.http.HttpURLConnection的實例....但我不認爲這是包含在Java SDK中的東西。這是否需要作爲外部jar導入?我看到它是OpenJDK的一部分。 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/net/www/protocol/http/HttpURLConnection.java – AKh

+2

它是Java JDK的一部分,在rt.jar中。 – EJP

+1

@AKh運行時環境將始終提供實現。 – Dev