简体   繁体   中英

HttpURLConnection Read time out

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".

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.

这意味着服务器在ReadTimeout中没有响应,可能是服务器关闭或处理线程被阻塞或服务器太忙。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM