android Retrofit下载图片
生活随笔
收集整理的這篇文章主要介紹了
android Retrofit下载图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?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接口調(diào)用:(主要就是這部分,@Streaming 和 Call<ResponseBody>?)
/** * 下載最新模板 * * @return */ @Streaming @GET Call<ResponseBody> downloadLatestFeature(@Url String fileUrl);
from : http://blog.csdn.net/newsolider2012/article/details/54644762
我的demo DownloadImage
總結(jié)
以上是生活随笔為你收集整理的android Retrofit下载图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 打码平台php源码,打码平台 远程打码
- 下一篇: [转] 一百本名著中的一百句话