gpt4 book ai didi

java - 如何以及为什么不在 URLConnection (DownloadFile) 上运行 "timeout"?

转载 作者:行者123 更新时间:2023-12-01 14:04:46 25 4
gpt4 key购买 nike

我有一个允许下载文件的异步方法。如果下载中途,我会删除连接(wifi或3g),永远不会发生超时。

始终停留在下一个循环中等待返回连接:

while ((count = input.read(data)) != -1) {
System.out.println("state 5");
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}

我愿意:

  private class DownloaderFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
...
try{
URLConnection connection = urlFinal.openConnection();
connection.setConnectTimeout(TIMEOUT_VALUE);
connection.setReadTimeout(TIMEOUT_VALUE);
connection.connect();
int fileLength = connection.getContentLength();

InputStream input = new BufferedInputStream(urlFinal.openStream());

OutputStream output = new FileOutputStream(folder + params[0]);

byte data[] = new byte[1024];
long total = 0;
int count;

while ((count = input.read(data)) != -1) {
//always wait here
System.out.println("state 5");
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();
} catch (SocketTimeoutException e) {
System.out.println("TIMEOUT!!! " + TIMEOUT_VALUE + " elapsed.");
callback.onDownloadEnd(DOWNLOAD_ERROR);
}
...
}
...

最佳答案

这不是一个很好的解决方案,但它确实有效。当我想到另一个解决方案时......

while ((count = input.read(data)) != -1) {
if (!isInternet(context)){
callback.onDownloadEnd(DOWNLOAD_ERROR);
return "error";
}
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}

关于java - 如何以及为什么不在 URLConnection (DownloadFile) 上运行 "timeout"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18993333/

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