处理 java.net.HttpURLConnection 到不存在的服务器
Handling java.net.HttpURLConnection to server that does not exist
在尝试连接到不存在的 host/server 时,我的程序似乎死了。使用调试器单步执行对我没有任何帮助,它到达 getResponseCode()
然后就停止工作了。据我所知,没有抛出异常,程序也没有 return.
这里是相关的代码片段:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
当连接到有效的 URL 时,它工作正常。
我修好了,我需要在打开连接后添加http.setConnectTimeout(10000);
。显然,无论默认超时设置多长,以至于它似乎根本不会给出响应,即使让应用程序打开几分钟也是如此。
在尝试连接到不存在的 host/server 时,我的程序似乎死了。使用调试器单步执行对我没有任何帮助,它到达 getResponseCode()
然后就停止工作了。据我所知,没有抛出异常,程序也没有 return.
这里是相关的代码片段:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
当连接到有效的 URL 时,它工作正常。
我修好了,我需要在打开连接后添加http.setConnectTimeout(10000);
。显然,无论默认超时设置多长,以至于它似乎根本不会给出响应,即使让应用程序打开几分钟也是如此。