HttpURLConnection读取超时

时间:2013-03-16 04:40:06

标签: java httpurlconnection socket-timeout-exception

我有以下代码来下载文件表单网址

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();

此代码工作正常,但有时我遇到以下错误:

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)

没有任何网络丢失。有没有其他方法来配置“ReadTimeout”。

2 个答案:

答案 0 :(得分:1)

这个问题没有意义。您设置了读取超时,您有一个读取超时。如果你比预期的更早得到它,将它设置得更长。您需要的唯一“配置读取超时”的另一种方法是更改​​超时值。应该是什么,只有你知道,因为只有你知道你为什么要设置它。十秒对我来说似乎太短了。

注意,您不需要继续重新创建读取缓冲区。你只是在制造大量的垃圾。

答案 1 :(得分:0)

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