user754740
user754740

Reputation: 117

Download URL content with timeout

I want to download the URL content in java with a specified download time. For ex: i want to have a maximum download timeout of 10 seconds for www.yahoo.com. If download takes more than 10s, then an error should be thrown. I have written the code for opening a connection and downloading the entire contents. But how do i set the download timeout? Here is the code snippet:

        StringBuilder text = new StringBuilder();

        urlconn = (HttpURLConnection)url.openConnection();
        urlconn.setConnectTimeout(100000);
      //urlconn.setInstanceFollowRedirects(false);
        urlconn.setRequestMethod("GET");
        urlconn.connect();
        buf = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); 
        while((line = buf.readLine()) != null)
            text.append(line);
        System.out.println(url + "=> "+ urlconn.getResponseCode());

Upvotes: 3

Views: 6666

Answers (2)

Asaph
Asaph

Reputation: 162801

Use URLConnection.setReadTimeOut().

Upvotes: 2

BalusC
BalusC

Reputation: 1108722

You can set it by URLConnection#setReadTimeout().

urlconn.setReadTimeout(10000); // 10 sec
// ...

Upvotes: 4

Related Questions