Retrofit 2 - 如何从服务器下载文件

如何声明Retrofit请求

如果你在阅读本文前没有写过任何一行Retrofit请求代码,那么最好看一下前面几篇博客。对于很多Retrofit使用者来说:定义一个下载文件的请求与其他请求几乎无异:

1
2
3
4
5
6
7
// option 1: a resource relative to your base URL
@GET("/resource/example.zip")
Call<ResponseBody> downloadFileWithFixedUrl();

// option 2: using a dynamic URL
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);

如果你要下载的文件是一个静态资源(存在于服务器上的同一个地点),Base URL指向的就是所在的服务器,这种情况下可以选择使用方案一。正如你所看到的,它看上去就像一个普通的Retrofit 2请求。值得注意的是,我们将ResponseBody作为了返回类型。Retrofit会试图解析并转换它,所以你不能使用任何其他返回类型,否则当你下载文件的时候,是毫无意义的。

第二种方案是Retrofit 2的新特性。现在你可以轻松构造一个动态地址来作为全路径请求。这对于一些特殊文件的下载是非常有用的,也就是说这个请求可能要依赖一些参数,比如用户信息或者时间戳等。你可以在运行时构造URL地址,并精确的请求文件。如果你还没有试过动态URL方式,可以翻到开头,看看这篇专题博客Retrofit 2中的动态URL

哪一种方案对你有用呢,我们接着往下看。

如何调用请求

声明请求后,实际调用方式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);

Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);

call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.d(TAG, "file download was a success? " + writtenToDisk);
} else {
Log.d(TAG, "server contact failed");
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});

如果你对ServiceGenerator.create()感到困惑,可以阅读我们的第一篇博客 。一旦创建了service,我们就能像其他Retrofit调用一样做网络请求了。

还剩下一件很重要的事,隐藏在代码块中的writeResponseBodyToDisk()函数:负责将文件写进磁盘。

如何保存文件

writeResponseBodyToDisk()方法持有ResponseBody对象,通过读取它的字节,并写入磁盘。代码看起来比实际略复杂:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private boolean writeResponseBodyToDisk(ResponseBody body) {  
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png");

InputStream inputStream = null;
OutputStream outputStream = null;

try {
byte[] fileReader = new byte[4096];

long fileSize = body.contentLength();
long fileSizeDownloaded = 0;

inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);

while (true) {
int read = inputStream.read(fileReader);

if (read == -1) {
break;
}

outputStream.write(fileReader, 0, read);

fileSizeDownloaded += read;

Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}

outputStream.flush();

return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}

if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}

大部分都是一般Java I/O流的样板代码。你只需要关心第一行代码就行了,也就是文件最终以什么命名被保存。当你做完这些工作,就能够用Retrofit来下载文件了。

但是我们并没有完全做好准备。而且这里存在一个大问题:默认情况下,Retrofit在处理结果前会将整个Server Response读进内存,这在JSON或者XML等Response上表现还算良好,但如果是一个非常大的文件,就可能造成OutofMemory异常。

如果你的应用需要下载略大的文件,我们强烈建议阅读下一节内容。

当心大文件:请使用@Streaming!

如果下载一个非常大的文件,Retrofit会试图将整个文件读进内存。为了避免这种现象的发生,我们添加了一个特殊的注解来声明请求。

1
2
3
@Streaming
@GET
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);

声明@Streaming并不是意味着你需要观察一个Netflix文件。它意味着立刻传递字节码,而不需要把整个文件读进内存。值得注意的是,如果你使用了@Streaming,并且依然使用以上的代码片段来进行处理。Android将会抛出android.os.NetworkOnMainThreadException异常。

因此,最后一步就是把这些操作放进一个单独的工作线程中,例如ASyncTask:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final FileDownloadService downloadService =  
ServiceGenerator.create(FileDownloadService.class);

new AsyncTask<Void, Long, Void>() {
@Override
protected Void doInBackground(Void... voids) {
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");

boolean writtenToDisk = writeResponseBodyToDisk(response.body());

Log.d(TAG, "file download was a success? " + writtenToDisk);
}
else {
Log.d(TAG, "server contact failed");
}
}
return null;
}
}.execute();

至此,如果你能够记住@Streaming的使用和以上代码片段,那么就能够使用Retrofit高效下载大文件了。

文/小鄧子(简书作者)
原文链接:http://www.jianshu.com/p/92bb85fc07e8