gpt4 book ai didi

java - HttpURLConnection 不响应也不抛出异常

转载 作者:行者123 更新时间:2023-12-01 06:11:02 31 4
gpt4 key购买 nike

我正在尝试发送一个 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com