使用Retrofit 2 + RxJava 2接收Gzip JSON响应

时间:2018-01-10 07:29:45

标签: android json gzip retrofit2 rx-java2

我试图以gzip json的形式接收一些数据,根据Jesse Wilson OkHttp的this answer自动解压缩,我不需要做任何事情。

所以我的问题是,我可以像这样收到gzipped的Json吗? :

apiService.getMessages().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableSubscriber<MessagesGet>() {
                    @Override
                    public void onNext(MessagesGet messagesGet) {



                        Timber.d("GET MESSAGES DATA READY TO HANDLE");

                    }

                    @Override
                    public void onError(Throwable t) {

                        Timber.e("ERROR GETTING MESSAGES");

                    }

                    @Override
                    public void onComplete() {

                        Timber.e("GETMESSAGES COMPLETED");

                    }
                });

@Headers({
            "Content-Type: application/json;charset=utf-8",
            "Accept: application/json"
    })
    @GET("getmessages")
    Flowable<MessagesGet> getMessages();

1 个答案:

答案 0 :(得分:0)

正如所讨论的那样..

  

服务界面。 您声明API的位置

@Headers("Content-Type: application/x-gzip")
@GET(Apis.GET_PATH)
Single<Response<ResponseBody>> downloadGzip(@Path(value = "path", encoded = true) String path);
  

Retrofit + RxJava config

public <S> S createService(Class<S> serviceClass) {


    OkHttpClient.Builder mHttpClient = new OkHttpClient.Builder();
    mHttpClient.connectTimeout(60, TimeUnit.SECONDS);
    mHttpClient.readTimeout(60, TimeUnit.SECONDS);
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

    if (BuildConfig.DEBUG) {
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    } else {
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    }

    mHttpClient.addInterceptor(logging);

    return new Retrofit.Builder()
            .baseUrl(baseURL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(mHttpClient.build())
            .build()
            .create(serviceClass);

}
  

触发GZIP下载

ApiService apiService = serviceGenerator.createServiceForm(ApiService.class);

apiService.downloadGzip(apiEndPoint) // apiEndPoint is direct download URL of GZIP
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<Response<ResponseBody>>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                    AppLogger.i(LOGGER, "gzip download ->" + "subscribed");
                }

                @Override
                public void onSuccess(Response<ResponseBody> responseBodyResponse) {
                //responseBodyResponse contains gzip
                    AppLogger.i(LOGGER, "gzip download -> " + " success");


                    // read gzip 
                    ByteArrayInputStream bais = null;
                    try {
                        bais = new ByteArrayInputStream(responseBodyResponse.body().bytes());

                        GZIPInputStream gzis = new GZIPInputStream(bais);
                        InputStreamReader reader = new InputStreamReader(gzis);
                        BufferedReader in = new BufferedReader(reader);

                        String readed;
                        StringBuilder gzipResponseString = new StringBuilder();
                        while ((readed = in.readLine()) != null) {
                            gzipResponseString.append(readed); //write gzip data in StringBuilder
                        }

                        AppLogger.i(LOGGER, "Gzip string->" + gzipResponseString);


                    } catch (IOException e) {
                        AppLogger.e(LOGGER, "gzip extract exception->" + e.getLocalizedMessage(), e);
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    AppLogger.e(LOGGER, "gzip failed->" + throwable.getMessage(), throwable);
                }
            });

您可以根据自己的要求继续使用DisposableSubscriber