Retrofit通过Url下载图片
1.首先工具类:
/** * ClassName:DownloadImageUtils * Description TODO 下载图片 * created by 漠天 * Data 2016/12/20 11:35 */ public class DownloadImageUtils { /** * 下载图片到SD卡 * @param mApi * @param url * @param imageName */ public static void downloadLatestFeature(AppServiceApi mApi, final String url, final String imageName){ Call<ResponseBody> resultCall = AppService.downloadLatestFeature(mApi,url); resultCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { writeResponseBodyToDisk(imageName,response.body()); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); } /** * 保存下载的图片流写入SD卡文件 * @param imageName xxx.jpg * @param body image stream */ public static void writeResponseBodyToDisk(String imageName, ResponseBody body) { if(body==null){ ToastUtils.showToast("图片源错误"); return; } try { InputStream is = body.byteStream(); File fileDr = new File(APP_IMAGE_DIR); if (!fileDr.exists()) { fileDr.mkdir(); } File file = new File(APP_IMAGE_DIR, imageName); if (file.exists()) { file.delete(); file = new File(APP_IMAGE_DIR, imageName ); } 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(); } } }
2.接口方法:
/** * 下载最新模板图片 * @param api */ public static Call<ResponseBody> downloadLatestFeature(AppServiceApi api, String imageUrl) { return api.downloadLatestFeature(imageUrl); }
3.Retrofit接口调用:(主要就是这部分,@Streaming 和 Call<ResponseBody> )
/** * 下载最新模板 * * @return */ @Streaming @GET Call<ResponseBody> downloadLatestFeature(@Url String fileUrl);
from : http://blog.csdn.net/newsolider2012/article/details/54644762