【问题标题】:HTTP response throw error gzip: invalid headerHTTP 响应抛出错误 gzip: invalid header
【发布时间】:2020-02-12 04:50:57
【问题描述】:

不明白哪里出了问题。 ioutil.ReadAll 应该像其他 URL 一样使用 gzip。

可以通过网址复制:romboutskorea.co.kr

错误:

gzip:标题无效

代码:

resp, err := http.Get("http://" + url)
            if err == nil {
                defer resp.Body.Close()

                if resp.StatusCode == http.StatusOK {
                    fmt.Printf("HTTP Response Status : %v\n", resp.StatusCode)
                    bodyBytes, err := ioutil.ReadAll(resp.Body)
                    if err != nil {
                        fmt.Printf("HTTP Response Read error. Url: %v\n", url)
                        log.Fatal(err)
                    }
                    bodyString := string(bodyBytes)

                    fmt.Printf("HTTP Response Content Length : %v\n", len(bodyString))
                }
            }

【问题讨论】:

  • Disabling compression 似乎有效(因此 Go 不请求压缩并忽略 Content-Encoding 响应标头)。全局禁用压缩:http.DefaultTransport.(*http.Transport).DisableCompression = true.
  • 一般来说,通过网络通信时会出现错误,您应该优雅地处理错误,而不是调用log.Fatal

标签: http go response


【解决方案1】:

本站的回复有误。它声称使用 gzip 编码,但实际上并没有压缩内容。响应如下所示:

HTTP/1.1 200 OK
...
Content-Encoding: gzip
...
Transfer-Encoding: chunked
Content-Type: text/html; charset=euc-kr

8000
<html>
<head>
...

“8000”来自分块传输编码,但“...”是未分块响应正文的开头。显然,即使声称是这样,它也没有被压缩。

看起来浏览器只是通过忽略错误的编码规范来绕过这个损坏的站点。浏览器实际上可以解决许多损坏的问题,这些问题并没有真正增加供应商解决这些问题的动力:(但你可以看到curl 将失败:

$ curl -v --compressed http://romboutskorea.co.kr/main/index.php?
...
< HTTP/1.1 200 OK
< ...
< Content-Encoding: gzip
< ...
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=euc-kr
< 
* Error while processing content unencoding: invalid code lengths set
* Failed writing data
* Curl_http_done: called premature == 1
* Closing connection 0
curl: (23) Error while processing content unencoding: invalid code lengths set

Python 也是如此:

$ python3 -c 'import requests; requests.get("http://romboutskorea.co.kr/main/index.php?")'
...
requests.exceptions.ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check'))

【讨论】:

    【解决方案2】:

    我明白了

    Content-Type: text/html; charset=euc-kr
    Content-Encoding: gzip
    

    检查正文内容:as in here,它可能是一个 HTTP 响应,其中正文首先使用 gzip 压缩,然后使用分块传输编码进行编码。

    需要NewChunkedReader,如in this example

    【讨论】:

      猜你喜欢
      • 2020-06-17
      • 2022-07-27
      • 2019-01-29
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      相关资源
      最近更新 更多