我目前正在编写一个简单的方法来快速构建 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。这个异常是什么?是什么原因导致这种情况发生?发生这种情况时我的应用程序应如何表现?
非常感谢大家, 威廉
最佳答案
MalformedURLException:当 URL 格式不正确时(例如 URL =“?@fake”) ProtocolException:表示底层协议(protocol)有错误(可能是SSL证书无效之类的)
IO异常 您没有收到 MalformedURLException 仅表明您提供的字符串 URL 的结构是正确的。它不保证相应主机存在并且可访问。它也不保证在连接到主机或对该主机执行任何读取或写入期间不会出现问题。因此,在打开与所需主机的连接时,如果出现问题(主机无法访问)或在连接握手期间出现读/写错误,您可能会收到 IOException。
关于java - 如何处理 java.net.URL.openConnection() 抛出的 IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15555852/