我正在尝试为访问相应网页内容的网址集合发送HTTP request
。但不知何故,对于少数网址,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();行中空闲。如何防止或至少跳过这种情况?
答案 0 :(得分:0)
您可以设置超时:
$scope.tinymceOptions.style_formats = [
{ title: 'test', selector : 'a', classes: 'sampletest'}
];
然后捕获java.net.SocketTimeoutException。
如果在建立连接之前超时到期,则a 引发java.net.SocketTimeoutException。超时为零 被解释为无限超时。
请参阅http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setConnectTimeout%28int%29
答案 1 :(得分:-1)
您需要指定套接字读取超时(SO超时)。 Defualt是无限的。因此,如果没有指定,线程将无限期地(理论上)读取。