回答

6

javadoc

將分別返回200和401。如果沒有代碼可以從響應中辨別出來(即響應不是有效的HTTP),則返回-1。

返回: HTTP狀態碼或-1

拋出: IOException - 如果錯誤發生在連接到服務器。

如果代碼尚未知道(尚未向服務器請求),則表示連接已打開且連接已完成(此時可能發生IOException)。

如果我們看一看到源代碼中,我們有:

public int getResponseCode() throws IOException { 
    /* 
    * We're got the response code already 
    */ 
    if (responseCode != -1) { 
     return responseCode; 
    } 

    /* 
    * Ensure that we have connected to the server. Record 
    * exception as we need to re-throw it if there isn't 
    * a status line. 
    */ 
    Exception exc = null; 
    try { 
     getInputStream(); 
    } catch (Exception e) { 
     exc = e; 
    } 

    /* 
    * If we can't a status-line then re-throw any exception 
    * that getInputStream threw. 
    */ 
    String statusLine = getHeaderField(0); 
    if (statusLine == null) { 
     if (exc != null) { 
      if (exc instanceof RuntimeException) 
       throw (RuntimeException)exc; 
      else 
       throw (IOException)exc; 
     } 
     return -1; 
    } 
    ... 
相關問題