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

标签 android json gzip retrofit2 rx-java2

根据 this answer,我正在尝试接收一些数据作为 gzipped json作者:Jesse Wilson OkHttp 自动解压缩,我无需执行任何操作。

所以我的问题是,我可以像这样接收压缩后的 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();

最佳答案

正如所讨论的..

Service interface. where you declare APIs

@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);

}

Trigger GZIP Download

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

关于android - 使用 Retrofit 2 + RxJava 2 接收 Gzip JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182317/

相关文章:

android - 如何在 Android 应用程序中将 SD 卡图像添加到电子邮件正文中

java - jackson 错误意外字符 ('}'(代码 125))

java - 使用 Apache Commons Compress 的压缩级别

node.js - 使用 zlib 压缩多个文件

nginx - 使用 nginx 启用 gzip 压缩

java - 带有 android 支持库 v7 的 maven android 插件

java - 将 30 分钟添加到 java 中的当前时间

android - 如何通过处理程序从 IntentService 多次调用 WebView Activity ?

java - 如何知道mysql表中数据被更新(即数据删除、修改或插入),从而更新java中的json对象

javascript - 在一个循环中生成一组标记,并为所有标记分配不同的弹出窗口