Java URL连接超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3163693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:00:12  来源:igfitidea点击:

Java URLConnection Timeout

javatimeoutconnecturlconnection

提问by Chris

I am trying to parse an XML file from an HTTP URL. I want to configure a timeout of 15 seconds if the XML fetch takes longer than that, I want to report a timeout. For some reason, the setConnectTimeout and setReadTimeout do not work. Here's the code:

我正在尝试从 HTTP URL 解析 XML 文件。如果 XML fetch 需要更长的时间,我想配置 15 秒的超时,我想报告超时。出于某种原因, setConnectTimeout 和 setReadTimeout 不起作用。这是代码:

          URL url = new URL("http://www.myurl.com/sample.xml");
          URLConnection urlConn = url.openConnection();
          urlConn.setConnectTimeout(15000);
          urlConn.setReadTimeout(15000);
          urlConn.setAllowUserInteraction(false);         
          urlConn.setDoOutput(true);

          InputStream inStream = urlConn.getInputStream();
          InputSource input = new InputSource(inStream);

And I am catching the SocketTimeoutException.

我正在捕获 SocketTimeoutException。

Thanks Chris

谢谢克里斯

回答by Mat B.

Try this:

尝试这个:

       import java.net.HttpURLConnection;

       URL url = new URL("http://www.myurl.com/sample.xml");

       HttpURLConnection huc = (HttpURLConnection) url.openConnection();
       HttpURLConnection.setFollowRedirects(false);
       huc.setConnectTimeout(15 * 1000);
       huc.setRequestMethod("GET");
       huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
       huc.connect();
       InputStream input = huc.getInputStream();

OR

或者

       import org.jsoup.nodes.Document;

       Document doc = null;
       try {
           doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
       } catch (Exception e) {
           //log error
       }

And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url

并看看如何使用 Jsoup:http://jsoup.org/cookbook/input/load-document-from-url

回答by dino.keco

I have used similar code for downloading logs from servers. I debug my code and discovered that implementation of URLConnection which is returned is sun.net.www.protocol.http.HttpURLConnection.

我已经使用类似的代码从服务器下载日志。我调试我的代码并发现返回的 URLConnection 的实现是 sun.net.www.protocol.http.HttpURLConnection。

Abstract class java.net.URLConnection have two attributes connectTimeout and readTimeout and setters are in abstract class. Believe or not implementation sun.net.www.protocol.http.HttpURLConnection have same attributes connectTimeout and readTimeout without setters and attributes from implementation class are used in getInputStream method. So there is no use of setting connectTimeout and readTimeout because they are never used in getInputStream method. In my opinion this is bug in sun.net.www.protocol.http.HttpURLConnection implementation.

抽象类 java.net.URLConnection 有两个属性 connectTimeout 和 readTimeout,setter 属于抽象类。信不信由你实现 sun.net.www.protocol.http.HttpURLConnection 具有相同的属性 connectTimeout 和 readTimeout 没有设置器,并且在 getInputStream 方法中使用了来自实现类的属性。因此没有使用设置 connectTimeout 和 readTimeout 因为它们从未在 getInputStream 方法中使用。在我看来,这是 sun.net.www.protocol.http.HttpURLConnection 实现中的错误。

My solution for this was to use HttpClient and Get request.

我对此的解决方案是使用 HttpClient 和 Get 请求。

回答by xpmatteo

Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket

你在 Windows 上吗?Windows 上的底层套接字实现似乎不太支持 SO_TIMEOUT 选项。另请参阅此答案:客户端套接字上的 setSoTimeout 不会影响套接字

回答by kinghomer

You can manually force disconnection by a Thread sleep. This is an example:

您可以通过线程睡眠手动强制断开连接。这是一个例子:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

然后

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

回答by Arjen Rodenhuis

You can set timeouts for all connections made from the jvm by changing the following System-properties:

您可以通过更改以下系统属性为从 jvm 建立的所有连接设置超时:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

每个连接将在 10 秒后超时。

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

不需要设置“defaultReadTimeout”,但如果您需要控制读取,则显示为示例。