我正在使用Android应用程序,我正在从网址下载文件。一切都运行良好,但当互联网连接进入之间(打开连接后),下载超时永远不会发生,连接永远不会结束。
建议我解决此问题的解决方案
**URL url = new URL("fileURL");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000);
File file = new File(context.getFilesDir(), "" + filename);
// getting file length
int lenghtOfFile = connection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int status = (int) ((total * 100) / lenghtOfFile);
publishProgress("" + status);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close()**
答案 0 :(得分:1)
您可以使用Retrofit Library从服务器下载文件,
Retrofit在内部使用OkHttp
请参阅以下网址
https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server
final FileDownloadService downloadService =
ServiceGenerator.createService(FileDownloadService.class);
Call<ResponseBody> call =
downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody>
response) {
if (response.isSuccessful()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(FileDownloadActivity.this, response.body(), null);
Log.d(TAG, "file download was a success? " + writtenToDisk);
return null;
}
}.execute();
} else {
Log.d(TAG, "server contact failed");
}
}
您还可以将@Streaming注释用于大文件。 Retrofit也将处理大文件下载