gpt4 book ai didi

java - URLConnection 不遵守 ReadTimeout

转载 作者:行者123 更新时间:2023-11-30 03:12:54 26 4
gpt4 key购买 nike

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

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

关于java - URLConnection 不遵守 ReadTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com