我尝试在没有互联网连接的情况下运行这段代码,期望触发 IOException:
import java.net.*;
import java.io.*;
public class API_connect {
public static void main(String[] args) {
try {
URL API = new URL("http://api.football-data.org");
URLConnection API_connection = API.openConnection();
}
catch(MalformedURLException exception) {
System.out.print(exception);
}
catch(IOException exception) {
System.out.print(exception);
System.out.print("is something going on here?");
}
}
}
好吧...令我惊讶的是什么都没有打印出来,我也不知道为什么。缺少互联网连接不会是此处抛出 IOException 的主要原因吗?
最佳答案
openConnection()
实际上并不尝试连接:
It should be noted that a URLConnection instance does not establish the actual network connection on creation. This will happen only when calling URLConnection.connect().
尝试在其上调用 connect()
。
或者,您可以尝试以下操作:
new URL(...).openStream().read();
这实际上会尝试从该 url 读取 1 个字节,但会失败。
关于java - IOException Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47357519/