回答

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; 
    } 
    ... 
相关问题