使用 auth 进行 http 代理 [英] Go http proxy with auth

查看:28
本文介绍了使用 auth 进行 http 代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 PostForm 方法通过身份验证使用代理.如果我使用类似(简化)的东西:

I need to use a proxy with auth using PostForm method. If I use something like (simplified):

request, err := http.NewRequest("GET", url.String(), nil)
response, err := client.Do(request)

我可以轻松地执行 request.Header.Add("Proxy-Authorization", basicAuth) 并且它工作正常.但是现在,我正在编辑第三方包,并尝试在现有代码中添加代理:

I can with ease do request.Header.Add("Proxy-Authorization", basicAuth) and it works fine. But now, I am editing third-party package, and I try to add proxy to the existing code:

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

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

    resp, err := bot.Client.PostForm(method, params)

    auth := "username:password"
    basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) 
    resp.Header.Add("Proxy-Authorization", basicAuth)

它不起作用,在我看来,它在字符串 resp.Header.Add("Proxy-Authorization", basicAuth) 处失败.在这个例子中,没有身份验证的代理工作正常.有谁知道,在这种情况下,我可以使用带有 auth 的代理吗?

It does not work, and it fails, to my mind, at string resp.Header.Add("Proxy-Authorization", basicAuth). Proxy without auth works fine, in this example. Does anybody know, can I use proxy with auth in this case?

推荐答案

您正在尝试向响应添加标头,这不是您发送到服务器的内容,而是您收到的内容.您必须向请求添加标头和数据,您必须先组装它们,然后像​​这样执行它:

You are trying to add a header to a response, which isn't what you send to the server but what you receive. You have to add headers and data to the request, which you have to assemble first and then execute it like this:

data := url.Values{} // the form data
data.Add("foo-key", "some data")
req, err := http.NewRequest("POST","https://yoururl", strings.NewReader(data.Encode()))
auth := "username:password"
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Proxy-Authorization", basicAuth)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := bot.Client.Do(req)

然后您只需使用响应 (resp)

Then you just use the response (resp)

这篇关于使用 auth 进行 http 代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆