HttpUrlConnection 和 setReadTimeout() 方法
HttpUrlConnection and setReadTimeout() method
我想知道引发 "java.net.SocketTimeoutException readtime out" 的时间和原因。
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();
这里是 question.I 设置读取超时值 421,我在第 55 行采取 "java.net.SocketTimeoutException readtime out" 异常。
while ((len = is.read(buffer)) > 0) {
所以我成功地获取了输入流,但是当我开始 reading/writing 它时,我接受了这个 exception.And 我检查文件的 732 Kb 是否已传输,直到发生异常。
所以我真的很困惑it.Please 准确解释 readtimeout 方法。
在 read()
调用开始和从该点开始的指定超时到期之间没有数据到达时引发。也就是说,在超时时间内没有数据到达。
So I take the inputstream succesfully
不足为奇。它花费零时间并且在网络上什么也不做,因为您已经调用了 getResponseCode()
(并且什么也没做)。
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.
所以数据的end到达的很慢。
NB 421 毫秒对于读取超时来说太短了。应该是几十秒。
我想知道引发 "java.net.SocketTimeoutException readtime out" 的时间和原因。
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();
这里是 question.I 设置读取超时值 421,我在第 55 行采取 "java.net.SocketTimeoutException readtime out" 异常。
while ((len = is.read(buffer)) > 0) {
所以我成功地获取了输入流,但是当我开始 reading/writing 它时,我接受了这个 exception.And 我检查文件的 732 Kb 是否已传输,直到发生异常。
所以我真的很困惑it.Please 准确解释 readtimeout 方法。
在 read()
调用开始和从该点开始的指定超时到期之间没有数据到达时引发。也就是说,在超时时间内没有数据到达。
So I take the inputstream succesfully
不足为奇。它花费零时间并且在网络上什么也不做,因为您已经调用了 getResponseCode()
(并且什么也没做)。
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.
所以数据的end到达的很慢。
NB 421 毫秒对于读取超时来说太短了。应该是几十秒。