gpt4 book ai didi

http - 为什么 HTTP 客户端强制使用 Accept-Encoding header

转载 作者:行者123 更新时间:2023-12-01 20:25:56 25 4
gpt4 key购买 nike

示例代码:

package main

import (
"fmt"
"net/http"
"net/http/httputil"
)

func main() {
client := &http.Client{
Transport: &http.Transport{
DisableCompression: true,
},
}
url := "https://google.com"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return
}
//req.Header.Set("Accept-Encoding", "*")
//req.Header.Del("Accept-Encoding")
requestDump, err := httputil.DumpRequestOut(req, false)
if err != nil {
fmt.Println(err)
}

fmt.Println(string(requestDump))
client.Do(req)
}
输出:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
只有 req.Header.Set("Accept-Encoding", "*"未注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: *
只有 req.Header.Del("Accept-Encoding")未注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
两行都没有注释:
GET / HTTP/1.1
Host: google.com
User-Agent: Go-http-client/1.1
Accept-Encoding: gzip
是否 DisableCompression实际上对 HTTP 请求本身做了什么?
根据godocs:
    // DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.

最佳答案

根据文件:

DumpRequestOut is like DumpRequest but for outgoing client requests.It includes any headers that the standard http.Transport adds, such as User-Agent.


这意味着它将“接受编码:gzip”添加到打印线格式。
要测试实际写入连接的内容,您需要包装 Transport.DialTransport.DialContext提供记录写入数据的连接。
如果您使用的传输支持 httptrace (所有内置和“x/http/...”传输实现都支持),您可以设置一个 WroteHeaderField回调以检查写入的 header 字段。
但是,如果您只需要检查标题,则可以生成 httptest.Server .
@EmilePels 提供的游乐场链接:
https://play.golang.org/p/ZPi-_mfDxI8

关于http - 为什么 HTTP 客户端强制使用 Accept-Encoding header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63160864/

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