gpt4 book ai didi

java - 对 HttpClient[Java] 处理 gzip 响应有点困惑

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:38 26 4
gpt4 key购买 nike

我的应用程序向某个 api 服务发出 http 请求,该服务返回 gzip 压缩响应。如何确保响应确实是 gzip 格式?我很困惑为什么在发出请求后我不必解压缩它。

下面是我的代码:

public static String streamToString(InputStream stream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line;

try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
logger.error("Error while streaming to string: {}", e);
} finally {
try { stream.close(); } catch (IOException e) { }
}

return sb.toString();
}

public static String getResultFromHttpRequest(String url) throws IOException { // add retries, catch all exceptions
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet;
HttpResponse httpResponse;
InputStream stream;

try {
httpGet = new HttpGet(url);
httpGet.setHeader("Content-Encoding", "gzip, deflate");
httpResponse = httpclient.execute(httpGet);
logger.info(httpResponse.getEntity().getContentEncoding());
logger.info(httpResponse.getEntity().getContent());
if (httpResponse.getStatusLine().getStatusCode() == 200) {
stream = httpResponse.getEntity().getContent();
return streamToString(stream);
}
} catch (IllegalStateException e) {
logger.error("Error while trying to access: " + url, e);
}

return "";
}

也许它正在自动解压缩,但我希望至少看到一些迹象。

最佳答案

嗨,我来晚了,但这个答案可能会被面临同样问题的人使用。默认情况下,内容在响应中解压缩。因此,您必须使用以下代码禁用默认压缩:

CloseableHttpClient client = HttpClients.custom()
.disableContentCompression()
.build();

HttpGet request = new HttpGet(urlSring);
request.setHeader(HttpHeaders.ACCEPT_ENCODING, "gzip");

CloseableHttpResponse response = client.execute(request, context);
HttpEntity entity = response.getEntity();
Header contentEncodingHeader = entity.getContentEncoding();

if (contentEncodingHeader != null) {
HeaderElement[] encodings =contentEncodingHeader.getElements();
for (int i = 0; i < encodings.length; i++) {
if (encodings[i].getName().equalsIgnoreCase("gzip")) {
entity = new GzipDecompressingEntity(entity);
break;
}
}
}

String output = EntityUtils.toString(entity, Charset.forName("UTF-8").name());

关于java - 对 HttpClient[Java] 处理 gzip 响应有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21482965/

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