繁体   English   中英

URLConnection不遵守ReadTimeout

[英]URLConnection does not respect ReadTimeout

我在代码中使用URLConnection 我已将ReadTimeout设置为5秒,但没有生效。 当我关闭wifi时,会立即调用IO Exception。

 URLConnection conn;     
 conn = new URL(StringUrls[0]).openConnection();
 conn.setReadTimeout(5000);
 in = conn.getInputStream();


      try {
           len = in.read(buffer);
           bufOutstream.write(buffer, 0, len);
           bufOutstream.close();
         } catch (IOException e1) {
             e1.printStackTrace();
                        }

IO异常:

12-17 12:41:35.332  12761-13268/com.app.example W/System.err﹕ java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:542)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at libcore.net.http.UnknownLengthHttpInputStream.read(UnknownLengthHttpInputStream.java:41)
12-17 12:41:35.362  12761-13268/com.app.example W/System.err﹕ at java.io.InputStream.read(InputStream.java:163)

示例代码如打击,

它将尝试最多20次以读取正确的数据。

如果一次出现异常,则5秒钟后再试一次。

private static int currentRetryCount = 0;

public static void main(String[] args) throws InterruptedException {
    retryRead(20);
}

public static void retryRead(int maxRetryCount) throws InterruptedException {
    if (currentRetryCount <= maxRetryCount) {
        try {
            System.out.println("try count " + currentRetryCount);
            URLConnection conn;
            conn = new URL("").openConnection();
            conn.setReadTimeout(5000);
            conn.getInputStream();
            // if nothing happens,it just return
            return;
        } catch (Exception e) {
            // if exception raises,it will try again after 5 seconds
            Thread.sleep(5000);

            currentRetryCount++;
            retryRead(maxRetryCount);
        }
    }
}

也许您在寻找setConnectTimeout

connectTimeout是用于建立连接的超时。
readTimeout是建立连接后从输入流读取数据的超时。

另外,当您的Wifi处于关闭状态时,您立即获得IOException的原因是,如果没有活动的连接媒体,则无论超时如何,连接都会立即中止。

您想要什么效果?可以显示更多详细信息吗?

将ReadTimeOut设置为N秒,并不意味着总读取时间将少于N秒。

这意味着两个数据包之间的最长时间(通过连接,您将获得很多数据包)。

例如,如果在N秒内没有可用数据,则将引发SocketTimeoutException。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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