java - 为什么 HttpURLConnection.getResponseCode() 抛出 IOException?

标签 java httpresponse httpurlconnection urlconnection http-response-codes

<分区>

我可以看到 getResponseCode() 方法只是一个 getter 方法,它返回已经由之前发生的连接操作设置的 statusCode

那么在这种情况下,为什么会抛出 IOException
我错过了什么吗?

最佳答案

来自 javadoc :

It will return 200 and 401 respectively. Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

Returns: the HTTP Status-Code, or -1

Throws: IOException - if an error occurred connecting to the server.

意味着如果代码未知(尚未向服务器请求),连接将打开并完成(此时可能发生 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;
    }
    ...

关于java - 为什么 HttpURLConnection.getResponseCode() 抛出 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16332850/

相关文章:

java - 返回 List<WebElements> 周围的代理

java - 如何将结果从 alertDialog 传递到 onActivityResult

java - 将可扩展数组索引(Ix 和系列)移植到 Java

c# - 如何修复错误代码 CS1503?

java - 无法在 Java 中发送帖子表单

java - jre8 中 URLPermission 的 IllegalArgumentException

java - matcher.find() 返回 false 而它应该返回 true

python 如何处理http请求和响应

Tomcat 7 : RequestDumperFilter not logging HTTP Request/Response body

java - 使用多个 HttpURLConnection 并行发送的问题?