如何在 Retrofit2 中为多个图像加载 ResponseBody(有和没有 Rx)

How to load ResponseBody's for multiple images in Retrofit2 (with and without Rx)

我开发了一个接受JSON(由图片链接组成)的应用程序,然后通过这些链接,我得到了响应的header并拉出contentlength()contenttype()source() 以便将这些图片写入外部存储。

JSON 例子:

[
  {
    "imageUrl": "https://bipbap.ru/wp-content/uploads/2018/01/57a741c2d70811566558e141.png"
  },
  {
    "imageUrl": "https://bipbap.ru/wp-content/uploads/2018/01/57a741c2d70811566558e141.png"
  },
  {
    "imageUrl": "https://bipbap.ru/wp-content/uploads/2018/01/57a741c2d70811566558e141.png"
  },
  {
    "imageUrl": "https://bipbap.ru/wp-content/uploads/2018/01/57a741c2d70811566558e141.png"
  }
]

代码示例:

public interface RetrofitApi {

    @GET("bins/xdfi8")
    Call<List<Image>> getImage();

    @GET
    Call<ResponseBody> getImage(@Url String url);
}
</code>

// MainActivity.java

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.myjson.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

     final RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);

        Call<List<Image>> call = retrofitApi.getImages();


        call.enqueue(new Callback<List<Image>>() {
            @Override
            public void onResponse(Call<List<Image>> call, Response<List<Image>> response) {

                if (!response.isSuccessful()) {
                    textViewResult.setText("Code: " + response.code());
                    return;
                }

                List<Image> images = response.body();

                for (Image image : images) {
                    Call<ResponseBody> responseBodyCall = retrofitApi.getResponseBody(image.getImageUrl());
                    responseBodyCall.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            String content = "";
                            content += response.body().contentType().subtype() + "\n";
                            content += response.body().contentLength() + "\n\n";
                            // for example print contenttype and contentlength in TextView
                            textViewResult.append(content);
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });

            @Override
            public void onFailure(Call<List<Image>> call, Throwable t) {

            }
});
}

}

Image.java

   public class Image {

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    private String imageUrl;
}

目前一个电话被打入另一个电话,如何避免?

如果我们使用 RxJavaRetrofitApi 也对该方法感兴趣 将采用这种形式:

public interface RetrofitApi {

    @GET("bins/xdfi8")
    Observable<List<Image>> getImage();

    @GET
    Observable<Response<ResponseBody>> getImage(@Url String url);
}

假设你有这个 api:

public interface RetrofitApi {

    @GET("bins/xdfi8")
    Observable<List<Image>> getImage();

    @GET
    Observable<Response<ResponseBody>> getImage(@Url String url);
}

然后在activity:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.myjson.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

final RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);

retrofitApi.getImages() // Observable<List<Image>>
    .flatMapIterable(images -> images) // Observable<Image>
    .flatMap(image -> retrofitApi.getImage(image.getImageUrl()))
            .onErrorResumeNext(Observable.empty())) // Observable<ResponseBody>
    .subscribeOn(Schedulers.io()) // run using io scheduler
    .observeOn(AndroidSchedulers.mainThread()) // observe in main thread
    .subscribe(result -> {
        ...
        textViewResult.append(content);
    }, error -> {
        textViewResult.setText("Code: " + error);
    })