gpt4 book ai didi

java - 好的http 3 : how to decompress gzip/deflate response manually using Java/Android

转载 作者:行者123 更新时间:2023-12-01 23:22:16 24 4
gpt4 key购买 nike

我知道 okhttp3 库默认情况下会添加 header Accept-Encoding: gzip 并自动为我们解码响应。

我正在处理的问题是,如果我不添加 deflate 部分,则只接受以下 header :Accept-Encoding: gzip, deflate失败。现在,当我手动将该 header 添加到 okhttp 客户端时,该库不再为我执行解压缩。

我尝试了多种解决方案来获取响应并尝试手动解压缩该响应,但我总是遇到异常,即 java.util.zip.ZipException: Not in GZIP format,这是我到目前为止所尝试过的:

//decompresser
public static String decompressGZIP(InputStream inputStream) throws IOException
{
InputStream bodyStream = new GZIPInputStream(inputStream);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = bodyStream.read(buffer)) > 0)
{
outStream.write(buffer, 0, length);
}

return new String(outStream.toByteArray());
}


//run scraper
scrape(api, new Callback()
{
// Something went wrong
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e)
{
}

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException
{
if (response.isSuccessful())
{
try
{
InputStream responseBodyBytes = responseBody.byteStream();
returnedObject = GZIPCompression.decompress(responseBodyBytes);

if (returnedObject != null)
{
String htmlResponse = returnedObject.toString();
}
}
catch (ProtocolException e){}

if(response != null) response.close();
}
}
});



private Call scrape(Map<?, ?> api, Callback callback)
{
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String method = (String) api.get("method");
String url = (String) api.get("url");
Request.Builder requestBuilder = new Request.Builder().url(url);
RequestBody requestBody;

requestBuilder.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
requestBuilder.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
requestBuilder.header("Accept-Language", "en-US,en;q=0.5");
requestBuilder.header("Accept-Encoding", "gzip, deflate");
requestBuilder.header("Connection", "keep-alive");
requestBuilder.header("Upgrade-Insecure-Requests", "1");
requestBuilder.header("Cache-Control", "max-age=0");

Request request = requestBuilder.build();

Call call = client.newCall(request);
call.enqueue(callback);

return call;
}

请注意,响应 header 将始终返回 Content-Encoding: gzipTransfer-Encoding: chunked

还有一件事,我也尝试过 this topic 中的解决方案它仍然失败,并显示 D/OkHttp: java.io.IOException: ID1ID2:actual 0x00003c68 != Expected 0x00001f8b

任何帮助将不胜感激..

最佳答案

经过 6 个小时的挖掘,我找到了正确的解决方案,并且像往常一样,它比我想象的要容易,所以我基本上是在尝试解压缩一个未进行 gzip 压缩的页面,因为它失败了。现在,一旦我点击第二页(已压缩),我就会收到一个 gzip 压缩的响应,上面的代码应该处理它。另外,如果有人想要解决方案,我使用了修改后的拦截器,就像 this answer 中的拦截器一样。因此您不需要使用自定义函数来处理解压。

我修改了 unzip 方法,使 okhttp 拦截器 能够处理压缩和未压缩的响应:

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;
}
}
}

关于java - 好的http 3 : how to decompress gzip/deflate response manually using Java/Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com