Read from URL java

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

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.

Tags:

Java

Url

Timeout