Net

Retrofit下载(大)文件

2017-01-07  本文已影响217人  山岭巨人郭敬明

对于很多Retrofit使用者来说:定义一个下载文件的请求与其他请求几乎无异:

@GET("/resource/example.zip")
Call<ResponseBody> downloadFileWithFixedUrl();

or

@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);

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

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

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

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

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对象,通过读取它的字节,并写入磁盘。代码看起来比实际略复杂:

private boolean writeResponseBodyToDisk(ResponseBody body) {  
    try {
        // 改成自己需要的存储位置
        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 //添加这个注解用来下载大文件
@GET
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);

声明@Streaming并不是意味着你需要观察一个Netflix文件。它意味着立刻传递字节码,而不需要把整个文件读进内存。

使用Retrofit下载大文件踩过的坑

OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .readTimeout(5, TimeUnit.SECONDS)//
                .connectTimeout(5, TimeUnit.SECONDS)//
                .addInterceptor(new DownloadProgressInterceptor())
               ~~ .addInterceptor(new HttpLoggingInterceptor()  //去掉!去掉!去掉!~~
               ~~ .setLevel(HttpLoggingInterceptor.Level.BODY))  //去掉!去掉!去掉!~~
                .build();
ExecutorService executorService = Executors.newFixedThreadPool(1);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://f5.market.xiaomi.com/download/AppStore/")
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .callbackExecutor(executorService) //默认CallBack回调在主线程进行,当设置下载大文件时需设置注解@Stream 不加这句话会报android.os.NetworkOnMainThreadException
                .build();

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

上一篇 下一篇

猜你喜欢

热点阅读