66

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

5
  • 1
    Does it hang? What happens? Are you reading from the stream? Commented Jul 2, 2010 at 6:49
  • No it doesn't hang and no exceptions. After parsing my variables are simply empty. Commented Jul 2, 2010 at 6:54
  • 4
    Let's see more code then, please. Commented Jul 2, 2010 at 7:08
  • Have you solved the question? I experience the same problem.. Commented Apr 15, 2011 at 8:35
  • 2
    That's not how it works. A read timeout affects individual reads, not the total read time. Where's the rest of your code? Commented Feb 1, 2019 at 11:19

5 Answers 5

33

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

Sign up to request clarification or add additional context in comments.

2 Comments

with Java 7 (+) it works like expected: conn.setReadTimeout(1000*10*1); conn.setConnectTimeout(1000*10*1); // 10 seks to wait for connection waits exactly 10 secs for a connect and for data.
This only affects the connect timeout, not the read timeout. Doesn't answer the question in any way.
20

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

2 Comments

From documentation: void java.net.HttpURLConnection.disconnect() Indicates that other requests to the server are unlikely in the near future. Calling disconnect() should not imply that this HttpURLConnection instance can be reused for other requests. --> So the socket is not necessarily closed when disconnect() is called.
Beware that this code will try to disconnect in 5 seconds anyway, even if you connected successfully and want to continue using that connection.
14

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.

2 Comments

This is what I needed to get it working on both Windows and OSX
Only for HTTP. java.net.Socket doesn't use these.
9

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.

2 Comments

Both these attributes have worked for me for over 20 years.
1

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

1 Comment

Never seen this since about 1992. No evidence provided either here or in your link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.