christian Muller
christian Muller

Reputation: 5056

Java setReadTimeout() does not work

how and where would implement bellow a setReadTimeout or a setConnectTimeout? My tests bellow always throw me error its undefined before compiling

When there is no connection it blocks at in.readLine() and the app waits forever

try {
    URL url = new URL("http://mydomain/myfile.php");

    //url.setReadTimeout(5000); does not work

    InputStreamReader testi= new InputStreamReader(url.openStream());
    BufferedReader in = new BufferedReader(testi);

        //in.setReadTimeout(5000); does not work

    stri = in.readLine();   
    Log.v ("GotThat: ",stri);
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

thanks for your help

chris

Upvotes: 1

Views: 2064

Answers (1)

René Link
René Link

Reputation: 51473

Use the URLConnection.

 URL url = new URL("http://mydomain/myfile.php");
 URLConnection connection = url.openConnection()
 int timeoutMs = 2000;
 connection.setReadTimeout(timeoutMs );

 InputStream urlInputStream = connection.getInputStream();
 BufferedReader in = new BufferedReader(new InputStreamReader(urlInputStream));

 String firstLine = in.readLine();   
 System.out.println("GotThat: " + firstLine);
 in.close();

This works for me. Because of your comment christian Muller I tried it with several websites and adjusted the timeoutMs value. Set timeoutMs to 250 ms should cause a SocketTimeoutException. If you then increase it step by step you will see that finally you read a line.

For example if I try:

URL url = new URL("http://msdn.microsoft.com/en-US/");
URLConnection connection = url.openConnection();
int timeoutMs = 250;
connection.setReadTimeout(timeoutMs);

I get

Exception in thread "main" java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:695)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:640)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
    at test.Main.main(Main.java:25)

If I try the same with 550 timeoutMs it works:

 GotThat: <!DOCTYPE html>

Upvotes: 1

Related Questions