【发布时间】:2017-03-26 19:15:05
【问题描述】:
在尝试连接到不存在的主机/服务器时,我的程序似乎死了。使用调试器单步执行对我没有任何帮助,它会到达getResponseCode(),然后停止工作。根据我的判断,没有抛出异常,程序也没有返回。
这里是相关代码sn-p:
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 时,它可以正常工作。
【问题讨论】:
-
确保在任何情况下都读取输入流(尤其是错误)
标签: java http httpurlconnection