Java 了解 URLConnection.setReadTimeout()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24554342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:57:29  来源:igfitidea点击:

understanding URLConnection.setReadTimeout()

javatimeouturlconnection

提问by lviggiani

Consider the following snippet:

考虑以下片段:

URLConnection connection = target.openConnection();

connection.setConnectTimeout(5000); // 5 sec
connection.setReadTimeout(10000); // 10 sec

Does the connection.setReadTimeoutsets the maximum time available for STARTING read data or is it the maximum time available for COMPLETING read data?

是否connection.setReadTimeout设置了可用于 STARTING 读取数据的最长时间,还是可用于 COMPLETING 读取数据的最长时间?

My understaning is that with that, java has 10 seconds to start reading the next byte of data from the connection. There is no timeout for finishing read all data from the connection as we do not know how big the strean may be. Is it correct?

我的理解是,java 有 10 秒的时间开始从连接读取下一个字节的数据。完成从连接读取所有数据没有超时,因为我们不知道 strean 可能有多大。这是正确的吗?

采纳答案by Pesho

According to oracle docs, if no data is available for the read timeout period, exception can be thrown

根据oracle docs,如果读取超时期间没有可用数据,则可以抛出异常

A SocketTimeoutException can be thrown when reading from the returned input stream if the read timeout expires before data is available for read.

如果读取超时在数据可供读取之前到期,则在从返回的输入流读取时可能会抛出 SocketTimeoutException。

回答by Andrew_CS

It is for "starting" read data. The timeout is there to set a limit on how long the wait is for incoming data. The timeout doesn't apply when there is data available for reading.

它用于“开始”读取数据。超时用于设置等待传入数据的时间限制。当有数据可供读取时,超时不适用。

"If the timeout expires before there is data availablefor read, a java.net.SocketTimeoutExceptionis raised."

“如果在有可供读取的数据之前超时到期java.net.SocketTimeoutException则会引发 a。”

Oracle Reference

甲骨文参考

In short - your understanding is correct.

简而言之-您的理解是正确的。

回答by Sam

you are right! connection.setReadTimeoutnot mean read complete, it mean when wait for 10s, when there're no more data read in, will throw a timeoutexception.

你是对的!connection.setReadTimeout不是说读完成,是说等待10s,当没有更多的数据读入时,会抛出一个超时异常。