Sarvesh Thiruppathi
Sarvesh Thiruppathi

Reputation: 65

Is it necessary to set getConnectTimeout and getReadTimeout?

Is it necessary to use getConnectTimeout and getReadTimeout and why do we use it ?

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.connect();

Upvotes: 0

Views: 219

Answers (2)

gargkshitiz
gargkshitiz

Reputation: 2168

If connection timeout (time for connecting) and read timeout (time for reading response) are not specified, then the thread making this call will block forever. There could be an infinite-loop bug on the server side, but your code will be impacted. Never trust any code completely, especially when it is written by someone else. If these timings are specified, and timeout actually happens, you could handle the exception gracefully OR could retry for finite number of times (whatever your business says and approves).

Upvotes: 1

Napster
Napster

Reputation: 1373

Is it necessary to use getConnectTimeout and getReadTimeout

It is not necessary but it's a good practice if you want to give your users a good experience. No one likes to wait forever on a loading screen

Why do we use it?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data. We use it to make sure that the user doesn't have to wait forever if the connection is taking time. The default readTimeout and connectTimeout are zero for HttpUrlConnection. Which means that the user might have to wait for forever for the resource to load (This doesn't happen because socket times out)

Upvotes: 1

Related Questions