【问题标题】:How do I handle the IOException thrown by java.net.URL.openConnection()?如何处理 java.net.URL.openConnection() 抛出的 IOException?
【发布时间】:2013-03-21 18:55:20
【问题描述】:

我目前正在编写一个简单的方法来快速构建一个 HttpURLConnection,但我在理解发生的异常时遇到了一些问题。目前看起来是这样的:

public static HttpURLConnection buildConnection(String urlString) throws IOException{
    try{
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setReadTimeout(10000 /* 10 seconds */);
        connection.setConnectTimeout(10000 /* 10 seconds */);
        return connection;

    } catch (MalformedURLException e){
        // Impossible - All network URLs are taken from String resources
        Log.w(LOG_LABEL, "URL \"" + urlString + "\" was malformed");
        e.printStackTrace();
        return null;
    } catch (ProtocolException e){
        // Impossible - "GET" is a valid Request method
        e.printStackTrace();
        return null;
    }
}

我捕获并记录 MalformedURLException 和 ProtocolException 异常,因为我知道它们不可能发生。但是我抛出了 url.openConnection() 可能抛出的 IOException。这是什么异常?是什么原因造成的?发生这种情况时我的应用应该如何表现?

非常感谢大家, 威廉

【问题讨论】:

    标签: java android exception-handling httpurlconnection


    【解决方案1】:

    MalformedURLException:当 URL 的格式不正确时(例如 URL = "?@fake") ProtocolException:表示底层协议有错误(可能是SSL证书无效)

    IO异常 您没有得到 MalformedURLException 仅表明您提供的字符串 URL 的结构是正确的。它不保证相应的主机存在并且可以访问。它也不保证在连接到主机或对该主机执行任何读取或写入时不会出现问题。因此,如果出现问题(主机无法访问)或在连接握手期间出现读/写错误,则打开与所需主机的连接时,您可能会收到 IOException。

    【讨论】:

    • 谢谢格拉德温。这是一个很好的具体答案。我将首先重试处理 IOException,然后向用户显示一般的网络错误消息。
    【解决方案2】:

    网络连接问题 - 无法写入或接收底层套接字。

    【讨论】:

      【解决方案3】:

      您应该将 Javadoc 视为第一站。 http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html

      您应该能够通过检查他抛出异常的 causemessage 参数来获得原因(如果有)

      【讨论】:

        【解决方案4】:

        表示发生了某种 I/O 异常。 此类是由失败或中断的 I/O 操作产生的一般异常类。 希望这会有所帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-31
          • 2012-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-03
          相关资源
          最近更新 更多