android Retrofit下载图片

 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




我的demo DownloadImage





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漠天515

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值