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

前端 未结 2 2043
一生所求
一生所求 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 03:45

    There is a better way than reinventing the wheel. Just add the Content-Encoding header yourself.

    .addNetworkInterceptor((Interceptor.Chain chain) -> {
        Request req = chain.request();
        Headers.Builder headersBuilder = req.headers().newBuilder();
    
        String credential = Credentials.basic(...);
        headersBuilder.set("Authorization", credential);
    
        Response res = chain.proceed(req.newBuilder().headers(headersBuilder.build()).build());
    
        return res.newBuilder()
            .header("Content-Encoding", "gzip")
            .header("Content-Type", ""application/json")
            .build();
    })
    

    In fact, your code is a classic example of the evils of using internal code (like com.sun packages from the JDK). RealResponseBody doesn't have that constructor anymore.

提交回复
热议问题