【译】Retrofit 2
来源:互联网 发布:luarocks windows 编辑:程序博客网 时间:2024/04/29 02:15
本文转载自:http://www.jianshu.com/p/92bb85fc07e8
如何声明Retrofit请求
如果你在阅读本文前没有写过任何一行Retrofit请求代码,那么最好看一下前面几篇博客。对于很多Retrofit使用者来说:定义一个下载文件的请求与其他请求几乎无异:
// option 1: a resource relative to your base URL@GET("/resource/example.zip")Call<ResponseBody> downloadFileWithFixedUrl();// option 2: using a dynamic URL@GETCall<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 { // 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会试图将整个文件读进内存。为了避免这种现象的发生,我们添加了一个特殊的注解来声明请求。
@Streaming@GETCall<ResponseBody> downloadFileWithDynamicUrlAsync(@Url String fileUrl);
声明@Streaming
并不是意味着你需要观察一个Netflix文件。它意味着立刻传递字节码,而不需要把整个文件读进内存。值得注意的是,如果你使用了@Streaming
,并且依然使用以上的代码片段来进行处理。Android将会抛出android.os.NetworkOnMainThreadException
异常。
因此,最后一步就是把这些操作放进一个单独的工作线程中,例如ASyncTask
:
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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- 【译】Retrofit 2
- Retrofit 2 使用教程
- 开源库(2) - Retrofit
- Retrofit 2 动态URL
- 进阶2_OkHttp+Retrofit
- Retrofit 2 入门指南
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- Retrofit
- 在geth客户端调用已部署的智能合约
- Java技术常用设计模式(五)--- 观察者模式
- 防止form表单重复提交
- java 识别图片相似度及图片是否相同
- 深入浅出JMS(一)--JMS基本概念
- 【译】Retrofit 2
- 使用重置按钮,重置表单信息
- 实例分享--语音和自然语言控制智能家居
- java--竖线分隔符|
- Python(一)
- Android面试整理
- 关于基类和派生类的构造函数和析构函数的执行顺序问题
- 【Unity】微信登录后将头像存为bytes,将bytes读取成sprite图片
- 数据结构复习之–“Shell排序”-JAVA实现