Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from URL java

Tags:

java

url

timeout

I'm trying to read URL in java, and it works as long as the URL is loading in browser.

But if it is just cylcing in the browser and not loading that page when I'm trying to open it in my browser, my java app just hangs, it will probably wait forever given enough time. How do I set timeout on that or something, if its loading for more than 20 seconds that I stop my application?

I'm using URL

Here is a relevant part of the code :

    URL url = null;
    String inputLine;

    try {
        url = new URL(surl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    BufferedReader in;
    try {
        in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
like image 208
Gandalf StormCrow Avatar asked Jun 07 '11 22:06

Gandalf StormCrow


2 Answers

I don't know how u are using the URL class. It would have been better if post a snippet. But here is a way that works for me. See if it helps in your case:

    URL url = new URL(urlPath);
    URLConnection con = url.openConnection();
    con.setConnectTimeout(connectTimeout);
    con.setReadTimeout(readTimeout);
    InputStream in = con.getInputStream();
like image 187
knurdy Avatar answered Nov 03 '22 00:11

knurdy


The URL#openStream method is actually just a shortcut for openConnection().getInputStream(). Here is the code from the URL class:

public final InputStream openStream() throws java.io.IOException {
  return openConnection().getInputStream();
}
  • You can adjust settings in the client code as follows:

    URLConnection conn = url.openConnection();
    // setting timeouts
    conn.setConnectTimeout(connectTimeoutinMilliseconds);
    conn.setReadTimeout(readTimeoutinMilliseconds);
    InputStream in = conn.getInputStream();
    

Reference: URLConnection#setReadTimeout, URLConnection#setConnectTimeout

  • Alternatively, you should set the sun.net.client.defaultConnectTimeout and sun.net.client.defaultReadTimeout system property to a reasonable value.
like image 42
Piyush Mattoo Avatar answered Nov 02 '22 23:11

Piyush Mattoo