Use retrofit to download image file

后端 未结 4 949
一个人的身影
一个人的身影 2020-12-10 07:06

I use Retrofit 1.6.0 on my Android project,

the request url:

https://example.com/image/thumbs/filename/sample.png

My interface like this:

<         


        
4条回答
  •  再見小時候
    2020-12-10 07:34

    Of course we usually use Picasso to load image, but sometimes we really need use Retrofit to load a special image (like fetch a captcha image), you need add some header for request, get some value from header of response (of course you can also use Picasso + OkHttp, but in a project you have already use Retrofit to handle most of net requests), so here introduce how to implement by Retrofit 2.0.0 (I have already implemented in my project).

    The key point is that you need use okhttp3.ResponseBody to receive response, else Retrofit will parse the response data as JSON, not binary data.

    codes:

    public interface Api {
        // don't need add 'Content-Type' header, it not works for Retrofit 2.0.0
        // @Headers({"Content-Type: image/png"})
        @GET
        Call fetchCaptcha(@Url String url);
    }
    
    Call call = api.fetchCaptcha(url);
    call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        // display the image data in a ImageView or save it
                        Bitmap bm = BitmapFactory.decodeStream(response.body().byteStream());
                        ivCaptcha.setImageBitmap(bm);
                    } else {
                        // TODO
                    }
                } else {
                    // TODO
                }
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
                // TODO
            }
        });
    

提交回复
热议问题