HttpURLConnection 不响应也不抛出异常

HttpURLConnection does not respond nor throw an exception

我正在尝试发送一个 HTTP request 用于访问相应页面内容的 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

您需要指定套接字读取超时(SO 超时)。默认为无穷大。因此,如果未指定,线程将无限期(理论上)读取。