Retrofit: how to parse GZIP'd response without Content-Encoding: gzip header

前端 未结 2 2065
一生所求
一生所求 2021-01-03 03:02

I\'m trying to process a server response which is GZIP\'d. The response comes with a header

Content-Type: application/x-gzip

but does not

2条回答
  •  情话喂你
    2021-01-03 04:08

    I figured it out. The idea is to add a custom interceptor which will take the not-yet-unzipped response, and unzip it 'manually' - do the same thing that OkHttp would do automatically based on Content-Encoding header, but without requiring that header.

    is like dis:

        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .addInterceptor(new UnzippingInterceptor());
        OkHttpClient client = clientBuilder.build();
    

    And the Interceptor is like dis:

    private class UnzippingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            return unzip(response);
        }
    }
    

    And the unzip function is like dis:

        // copied from okhttp3.internal.http.HttpEngine (because is private)
    private Response unzip(final Response response) throws IOException {
    
        if (response.body() == null) {
            return response;
        }
    
        GzipSource responseBody = new GzipSource(response.body().source());
        Headers strippedHeaders = response.headers().newBuilder()
                .removeAll("Content-Encoding")
                .removeAll("Content-Length")
                .build();
        return response.newBuilder()
                .headers(strippedHeaders)
                .body(new RealResponseBody(strippedHeaders, Okio.buffer(responseBody)))
                .build();
    }
    

提交回复
热议问题