javauser35
javauser35

Reputation: 1315

HttpUrlConnection and setReadTimeout() method

I want to know when and why the "java.net.SocketTimeoutException readtime out" is raised.

    URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(421);

        int responseCode = con.getResponseCode();

        InputStream is =    con.getInputStream();
        System.out.println("Inputstream done");

        FileOutputStream fos = fos = new FileOutputStream("D:\\tryfile\\file1.csv");

        byte[] buffer = new byte[4096];              //declare 4KB buffer
            int len;

            while ((len = is.read(buffer)) > 0) {

                fos.write(buffer, 0, len);
            }

          fos.close();
          is.close();

Here is the question.I set read timeout value 421 and I take "java.net.SocketTimeoutException readtime out" exception at that line 55.

while ((len = is.read(buffer)) > 0) {

So I take the inputstream succesfuly but when I start reading/writing it I take this exception.And I check that the 732 Kb of the file is transfered until the exception.

So I really confused about it.Please explain readtimeout method exactly.

Upvotes: 1

Views: 1745

Answers (1)

user207421
user207421

Reputation: 310957

It is raised when no data arrives between the inception of the read() call and the expiration of the specified timeout starting at that point. In other words, no data arrived within the timeout period.

So I take the inputstream succesfully

Not surprising. It takes zero time and does nothing on the network, as you have already called getResponseCode() (and done nothing with it).

but when I start reading/writing it I take this exception.

So the data was slow arriving.

And I check that the 732 Kb of the file is transfered until the exception.

So the end of the data was slow arriving.

NB 421ms is far too short for a read timeout. It should be tens of seconds.

Upvotes: 1

Related Questions