HttpURLConnection Read time out

Naresh picture Naresh · Mar 16, 2013 · Viewed 8k times · Source

I have a following code to download file form URL

HttpURLConnection urlConn = (HttpURLConnection)urlOfFile.openConnection();
urlConn.setConnectTimeout(5000);
urlConn.setReadTimeout(10000);

StatusInfo.fileSizeTobeDownload = urlConn.getContentLength();

InputStream reader = urlConn.getInputStream();

FileOutputStream writer = new FileOutputStream(downloadFolder+fileName);
byte[] buffer = new byte[1024]; 
int bytesRead = 0;  
while ((bytesRead = reader.read(buffer)) > 0) {
    writer.write(buffer, 0, bytesRead);
    buffer = new byte[1024];
    StatusInfo.fileSizeDownloaded+=bytesRead;
}
writer.close();
reader.close();

This code works fine, but sometime i got following error:

java.net.SocketTimeoutException: Read timed out
 at java.net.SocketInputStream.socketRead0(Native Method)
 at java.net.SocketInputStream.read(SocketInputStream.java:146)
 at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
 at sun.security.ssl.InputRecord.readV3Record(InputRecord.java:554)
 at sun.security.ssl.InputRecord.read(InputRecord.java:509)
 at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:850)
 at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:807)
 at sun.security.ssl.AppInputStream.read(AppInputStream.java:94)
 at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
 at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
 at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
 at sun.net.www.MeteredStream.read(MeteredStream.java:134)
 at java.io.FilterInputStream.read(FilterInputStream.java:133)
 at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:2582)
 at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:2577)

without any network drop. Is there any other way to configure "ReadTimeout".

Answer

user207421 picture user207421 · Mar 16, 2013

The question doesn't make sense. You set a read timeout, you got a read timeout. If you got it sooner than you expected, set it to be longer. The only 'other way to configure read timeout' you need is to change the timeout value. What that should be, only you know, as only you know why you're setting it. Ten seconds does seem too short to me.

NB you don't need to keep recreating the read buffer. You're just creating tons of garbage.