我正在尝试发送一个 HTTP 请求
以获取 URL 集合,以访问相应页面的内容。但不知何故,对于少数 URL,HttpURLConnection
不执行任何操作,并且程序保持空闲状态。
这是我的代码:
while(null != (line = br.readLine())){
URL url = new URL(line);
openConnection(url);
}
static void openConnection(URL url) {
URLConnection connection = url.openConnection();
if (connection instanceof HttpURLConnection) {
try{
httpConn = (HttpURLConnection) connection;
httpConn.setConnectTimeout(2000);
int statusCode = httpConn.getResponseCode();
if (statusCode <= 200 && statusCode < 300)
{
//do something
}
}
catch (ConnectException|java.lang.IllegalArgumentException ex) { java.util.logging.Logger.getLogger(CreateXMLtest.class.getName()).log(Level.SEVERE, null, ex);} //catch the possible exception.
catch (SSLHandshakeException |SocketException | SocketTimeoutException | UnknownHostException ex) {java.util.logging.Logger.getLogger(CreateXMLtest.class.getName()).log(Level.SEVERE, null, ex);}
catch (java.io.IOException ex) { java.util.logging.Logger.getLogger(CreateXMLtest.class.getName()).log(Level.SEVERE, null, ex);}
}
}
由于某些原因,程序在 ` int statusCode = httpConn.getResponseCode(); 行处空闲。如何防止或至少跳过这种情况?
最佳答案
您可以设置超时:
httpConn.setConnectTimeout(TIMEOUT); //milliseconds
httpConn.setReadTimeout(TIMEOUT);
然后捕获 java.net.SocketTimeoutException。
If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.
参见http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setConnectTimeout%28int%29
关于java - HttpURLConnection 不响应也不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34510617/