利用Retrofit下载资源文件,正常情况下应该这样写的:
public interface DownloadApiService {
@GET
Call<ResponseBody> downloadFile(@Url String url);
}
Call<ResponseBody> call = service.downloadFile();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
InputStream is = response.body().byteStream();
File file = new File(Environment.getExternalStorageDirectory(), "文件路径");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
fos.flush();
}
fos.close();
bis.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
这样下载单个文件,使用起来没有问题,但是如果多个文件一起下载就不是很方便了,还要在加上UI进度更新就更不方便了。假设下OnResponse能否直接返回下载的文件呢?和数据请求一样直接返回Json格式的数据结构,有了这个想法后我们看下Retrofit是怎么实现的。
public <APISERVICE> APISERVICE create(final String baseUrl,
final Class<APISERVICE> clazz) {
return new Retrofit.Builder().baseUrl(baseUrl)
.client(HttpClientHelper.getHttpClient())
.ad