经过6个小时的挖掘,我找到了正确的解决方案,而且和往常一样,它比我想象的要简单,所以我基本上是在尝试解压缩一个没有被gzip压缩的页面,因为它失败了。现在,一旦我进入第二页(它是压缩的),我就会得到一个gzip响应,上面的代码应该处理它。另外,如果有人想要这个解决方案,我使用了一个修改过的拦截器,就像
this answer
所以不需要使用自定义函数来处理解压。
我修改了
unzip
方法来生成okhttp
interceptor
处理压缩和未压缩的响应:
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().addInterceptor(new UnzippingInterceptor());
OkHttpClient client = clientBuilder.build();
private class UnzippingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return unzip(response);
// copied from okhttp3.internal.http.HttpEngine (because is private)
private Response unzip(final Response response) throws IOException
{
if (response.body() == null)
{
return response;
}
//check if we have gzip response
String contentEncoding = response.headers().get("Content-Encoding");
//this is used to decompress gzipped responses
if (contentEncoding != null && contentEncoding.equals("gzip"))
{
Long contentLength = response.body().contentLength();
GzipSource responseBody = new GzipSource(response.body().source());
Headers strippedHeaders = response.headers().newBuilder().build();
return response.newBuilder().headers(strippedHeaders)
.body(new RealResponseBody(response.body().contentType().toString(), contentLength, Okio.buffer(responseBody)))
.build();
}
else
{
return response;
}
}
}
}