
请大佬们帮忙看下,go 怎么才能通过代理成功发起请求
我也试了 php 也不行
python 代码
import requests def send_request_via_proxy(*args, **kwargs): baidu_proxy = 'http://cloudnproxy.baidu.com:443' kwargs['proxies'] = {'http': baidu_proxy, 'https': baidu_proxy} if 'headers' not in kwargs: kwargs['headers'] = {} if 'User-Agent' not in kwargs['headers']: kwargs['headers'][ 'User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 baiduboxapp/13.10.0.10' resp = requests.request(*args, **kwargs) print(resp.request.headers) print(resp.request) return resp if __name__ == '__main__': api = 'https://pubstatic.b0.upaiyun.com/?_upnode' ip_info = send_request_via_proxy('GET', api).json() print(ip_info['remote_addr']) print(ip_info['remote_addr_location']) go 代码
package main import ( "fmt" "io" "log" "net/http" "net/url" "time" ) func main() { URL, _ := url.Parse("http://cloudnproxy.baidu.com:443") client := &http.Client{ Transport: &http.Transport{ TLSHandshakeTimeout: 30 * time.Second, Proxy: http.ProxyURL(URL), }, } req, err := http.NewRequest("GET", "https://pubstatic.b0.upaiyun.com/?_upnode", nil) if err != nil { log.Fatal(err) } req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36(KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 baiduboxapp/13.10.0.10") resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() bodyText, err := io.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", bodyText) } 1 body007 2024-05-17 13:59:57 +08:00 这里有个 http 代理服务器,经过我的测试,你上面提供的 python 和 golang 代码都能正常执行。是不是你的代理服务器有特殊逻辑啊。 https://gist.github.com/jan-bar/b856c271712a6481260131dd66dd7ffe ![]() ![]() |
4 body007 2024-05-17 14:38:28 +08:00 |
7 body007 2024-05-17 14:57:05 +08:00 @ToPoGE #6 我的 py 和库版本如下,不知道是不是 python 和库不同版本行为不一致导致你的 python 能用,反正代码我是完全复制你上面给的额。 requests 2.31.0 Python 3.12.3 |
8 guanzhangzhang 2024-05-17 15:31:29 +08:00 你抓包你 python 的和 go 的 http 请求,然后 curl 发下看看 |
9 winterpotato 2024-05-17 21:05:21 +08:00 题外话,Go 的应用默认情况下会尊重 `http_proxy` 和 `https_proxy` 环境变量 。但是从楼上的回复来看,可能是你的代理的问题。 |
10 ToPoGE OP @winterpotato 实际上我疑问的就是代理,一个可以在 python 中使用一个在 Go 就没法用 |