gpt4 book ai didi

android - 下载文件时出现 InputStream 异常

转载 作者:行者123 更新时间:2023-11-30 02:23:07 24 4
gpt4 key购买 nike

我正在尝试从服务器下载 PPT 文件。它以字节为单位。

但在调试时我注意到输入流在运行时抛出 FileNotFound 异常。该文件确实存在于服务器上,这是我的代码,我们将不胜感激。

public class DownloadFileAsync extends AsyncTask<String, String, String> {


@Override
protected String doInBackground(String... aurl) {
int count;

try {
URL url = new URL(aurl[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", "Basic " + SharedPref.getAuthPrefValue());
connection.addRequestProperty("Device", BaseApplication.getCurrentDevice().getDevice().toString());
connection.addRequestProperty("DeviceId", BaseApplication.getCurrentDevice().getDeviceId());
connection.connect();

int lengthOfFile = connection.getContentLength();
Log.d("ANDRO_ASYNC", "Length of file: " + lengthOfFile);

InputStream input = new BufferedInputStream(url.openStream());
File sdcardDest = new File(Environment.getExternalStorageDirectory(), "Availo");
String finalDest = sdcardDest + File.separator + "Check1" + "." + "PPT";
OutputStream output = new FileOutputStream(finalDest);

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lengthOfFile));
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
e.printStackTrace();
}


return null;
}

我在 Mac 上使用 Charles(类似于 Windows 上的 fiddler)来查看我从服务器发送和接收的内容,服务器没有返回任何错误,尽管它显示了 6-7 秒的下载步骤,下载了大约 400 字节然后停止。

异常从输入流中抛出。

谢谢!

最佳答案

我建议你看看 DownloadManager系统服务。它专为您要执行的操作而设计:

(来自文档)

The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots

关于android - 下载文件时出现 InputStream 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197834/

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