gpt4 book ai didi

http - 为什么 Go 中的 http 客户端在发出 https 请求时会通过代理返回 Unauthorized?

转载 作者:数据小太阳 更新时间:2023-10-29 03:14:48 27 4
gpt4 key购买 nike

我一直在尝试通过代理从我一直在使用 Go 的客户端发出 GET 请求。

curl 等价物可能看起来有点像这样:

curl -v -x example.proxy.com:8080 -U username:password 'https://example.com'

虽然像这样的东西会起作用,但 Go 中的等价物似乎不起作用,这是一个例子:

auth := "username:password"

basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))

proxyURL, _ := url.Parse("http://example.proxy.com:8080")
url, _ := url.Parse("https://example.com")

transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
client := &http.Client{
Transport: transport,
}

request, _ := http.NewRequest("GET", url.String(), nil)
request.Header.Add("Proxy-Authorization", basic)
request.Header.Add("Proxy-Connection", "Keep-Alive")

response, _ := client.Do(request)

两者之间的唯一区别是 curl 命令在向 http 和 https url 发出请求时会成功,Go 代码将在 http 上工作,但在上面的示例中 (https://example. com,或任何其他 https URL),这将返回未授权状态。

我觉得我在这里遗漏了一些非常明显的东西,但似乎无法深入了解它。

最佳答案

您在 http.Request 上设置了一个 header ,该 header 被发送到上游服务器,而不是代理。您可以在代理 *url.URL 中设置基本身份验证:

proxyURL, _ := url.Parse("http://127.0.0.1:8080")
proxyURL.User = url.UserPassword("username", "password")

client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}

关于http - 为什么 Go 中的 http 客户端在发出 https 请求时会通过代理返回 Unauthorized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39487798/

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