[英]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.