Java URL连接超时

发布于 2024-09-07 13:33:58 字数 620 浏览 4 评论 0原文

我正在尝试从 HTTP URL 解析 XML 文件。我想将超时配置为 15 秒,如果 XML 获取时间超过该时间,我想报告超时。由于某种原因,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);

我正在捕获 SocketTimeoutException。

谢谢 克里斯

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:

          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.

Thanks
Chris

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

绮筵 2024-09-14 13:33:58

试试这个:

       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();

或者

       import org.jsoup.nodes.Document;

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

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

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

月隐月明月朦胧 2024-09-14 13:33:58

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

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

那么

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");
    }
}

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");
    }
}
注定孤独终老 2024-09-14 13:33:58

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

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

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

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

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

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

Every connection will time out after 10 seconds.

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

眸中客 2024-09-14 13:33:58

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

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

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

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.

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.

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

熟人话多 2024-09-14 13:33:58

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文