gpt4 book ai didi

java - 在 Java 中解压缩 GZIP HTTP 响应

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:18:06 25 4
gpt4 key购买 nike

我正在尝试使用 GZIPInputStream 解压缩 GZIP 压缩的 HTTP 响应。但是,当我尝试读取流时,我总是遇到相同的异常:java.util.zip.ZipException: invalid bit length repeat

我的 HTTP 请求 header :

GET www.myurl.com HTTP/1.0\r\n
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.2) Gecko/20100115 Firefox/3.6\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3\r\n
Accept-Encoding: gzip,deflate\r\n
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7\r\n
Keep-Alive: 115\r\n
Connection: keep-alive\r\n
X-Requested-With: XMLHttpRequest\r\n
Cookie: Some Cookies\r\n\r\n

在 HTTP 响应 header 的末尾,我得到 path=/Content-Encoding: gzip,然后是 gzip 压缩响应。

我尝试了 2 个类似的代码来解压缩:

更新:在下面的代码中,tBytes = ('path=/Content-Encoding: gzip'之后的字符串).getBytes ();

GZIPInputStream  gzip = new GZIPInputStream (new ByteArrayInputStream (tBytes));

StringBuffer szBuffer = new StringBuffer ();

byte tByte [] = new byte [1024];

while (true)
{
int iLength = gzip.read (tByte, 0, 1024); // <-- Error comes here

if (iLength < 0)
break;

szBuffer.append (new String (tByte, 0, iLength));
}

这是我在这个论坛上得到的:

InputStream     gzipStream = new GZIPInputStream   (new ByteArrayInputStream (tBytes));
Reader decoder = new InputStreamReader (gzipStream, "UTF-8");//<- I tried ISO-8859-1 and get the same exception
BufferedReader buffered = new BufferedReader (decoder);

我猜这是一个编码错误。

最好的问候,

比比皆是

最佳答案

您没有说明如何获得用于在此处设置 gzip 流的 tBytes:

GZIPInputStream  gzip = new GZIPInputStream (new ByteArrayInputStream (tBytes));

一种解释是您将整个 HTTP 响应包含在 tBytes 中。相反,它应该只是 HTTP header 之后的内容。

另一种解释是响应是chunked .

编辑:您将内容编码行之后的数据作为消息正文。然而,根据 HTTP 1.1 规范, header 字段没有按任何特定顺序出现,因此这是非常危险的。

HTTP specification 的这一部分所述, 请求或响应的消息正文不是在特定的头字段之后,而是在第一个空行之后:

Request (section 5) and Response (section 6) messages use the generic message format of RFC 822 [9] for transferring entities (the payload of the message). Both types of message consist of a start-line, zero or more header fields (also known as "headers"), an empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields, and possibly a message-body.

您仍然没有展示您是如何准确地组成 tBytes 的,但在这一点上我认为您错误地在您尝试解压缩的数据中包含了空行。消息正文在空行的 CRLF 字符之后开始。

我可以建议您使用 httpclient库而不是提取邮件正文?

关于java - 在 Java 中解压缩 GZIP HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2474193/

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