【问题标题】:Receiving Gzip JSON Response with Retrofit 2 + RxJava 2使用 Retrofit 2 + RxJava 2 接收 Gzip JSON 响应
【发布时间】:2018-01-10 07:29:44
【问题描述】:

根据 Jesse Wilson 的 this answer,我正在尝试以压缩 json 的形式接收一些数据,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();

【问题讨论】:

  • gzip 包含什么样的数据?
  • @Aks4125 字符串
  • 你试过了吗?它应该可以工作。
  • 您找到合适的解决方案了吗?我正在努力实现同样的目标。
  • @IgorGanapolsky 不太记得了,但我得到了响应压缩,而不是使用解压缩方法解压缩它gist.github.com/yfnick/227e0c12957a329ad138

标签: android json gzip retrofit2 rx-java2


【解决方案1】:

如前所述..

服务接口。 您声明 API 的位置

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

改造 + RxJava 配置

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

【讨论】:

  • 嗨,谢谢你的回答,但是这个没有解释发生了什么,所以你在这里做的是通过改造和 rxjava 获取 gzip 压缩的 json 文件并完全解压缩或一个一个解压缩细绳?什么是 getJsonByFormUrl() 方法?我怎么知道我正在以表单 url 编码的形式获取数据?我应该在哪里处理解压缩 json 的新请求?我有很多问题
猜你喜欢
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多