Use retrofit to download image file

后端 未结 4 947
一个人的身影
一个人的身影 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:38

    I am playing with rxjava and retrofit these days, I have a quick demo here. Talk is cheap, show you my code directly, hope it helps.

    public interface ImageService {
    
        String ENDPOINT = "HTTP://REPLACE.ME";
    
        @GET
        @Streaming
        Observable getThumbs(@Url String filepath);
    
        /********
         * Helper class that sets up a new services
         *******/
        class Instance {
    
            static ImageService instance;
    
            public static ImageService get() {
                if (instance == null)
                    instance = newImageService();
                return instance;
            }
    
            public static ImageService newImageService() {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(ImageService.ENDPOINT)
                        .addConverterFactory(BitmapConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();
                return retrofit.create(ImageService.class);
            }
        }
    }
    

    And I wrote my own BitmapConverterFactory to convert byte stream to bitmap:

    public final class BitmapConverterFactory extends Converter.Factory {
    
        public static BitmapConverterFactory create() {
            return new BitmapConverterFactory();
        }
    
    
        private BitmapConverterFactory() {
        }
    
        @Override
        public Converter responseBodyConverter(Type type, Annotation[] annotations,
                                                                     Retrofit retrofit) {
            if (type == Bitmap.class) {
                return new Converter(){
    
                    @Override
                    public Bitmap convert(ResponseBody value) throws IOException {
                        return BitmapFactory.decodeStream(value.byteStream());
                    }
                };
            } else {
                return null;
            }
        }
    
        @Override
        public Converter requestBodyConverter(Type type, Annotation[] annotations,
                                                              Retrofit retrofit) {
            return null;
        }
    }
    

    Gradle dependencies here:

    final RETROFIT_VERSION = '2.0.0-beta3'
    compile "com.squareup.retrofit2:retrofit:$RETROFIT_VERSION"
    compile "com.squareup.retrofit2:adapter-rxjava:$RETROFIT_VERSION"
    

    Cheers, vanvency

提交回复
热议问题