gpt4 book ai didi

curl - 来自 cURL 和 Golang POST 的不同响应 - 不明白为什么

转载 作者:IT王子 更新时间:2023-10-29 01:44:52 31 4
gpt4 key购买 nike

我正在尝试使用 golang 的 http 客户端从服务器获取响应。

我希望通过 go 执行的请求应该与以下 curl 命令相同:

curl  --data "fulladdress=22280+S+209th+Way%2C+Queen+Creek%2C+AZ+85142"  'http://www.homefacts.com/hfreport.html'

我编写了等效的 go 代码,还尝试使用名为 curl-to-go 的优质服务,它为上面的 curl 请求生成以下 go 代码:

 // Generated by curl-to-Go: https://mholt.github.io/curl-to-go

body := strings.NewReader(`fulladdress=22280+S+209th+Way%2C+Queen+Creek%2C+AZ+85142`)
req, err := http.NewRequest("POST", "http://www.homefacts.com/hfreport.html", body)
if err != nil {
// handle err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

resp, err := http.DefaultClient.Do(req)
if err != nil {
// handle err
}
defer resp.Body.Close()

问题是我一直在 curl 命令和 go 代码之间得到不同的响应。 curl 命令返回此响应正文:

<html><head><meta http-equiv="refresh" content="0;url=http://www.homefacts.com/address/Arizona/Maricopa-County/Queen-Creek/85142/22280-S-209th-Way.html"/></head></html>

这是预期的结果。然而,go 代码返回了一个很长的 HTML,这不是预期的结果。

我尝试将 --verbose 添加到 curl 命令以复制它的所有 header ,因此我通过我的 go 代码添加了以下 header :

req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", "curl/7.51.0")
req.Header.Set("Accept", "*/*")
req.Header.Set("Content-Length", "56")

但还是不高兴,go 代码的输出与 curl 的输出仍然不同。

关于如何从 go 获得相同的 curl 响应有什么想法吗?

最佳答案

感谢@u_mulder 为我指明了正确的方向。似乎默认的 go http 客户端默认遵循重定向 header ,而 curl 则没有。

这是在 go 和 curl 之间生成相同结果的更新代码:

body := strings.NewReader(`fulladdress=22280+S+209th+Way%2C+Queen+Creek%2C+AZ+85142`)
req, err := http.NewRequest("POST", "http://www.homefacts.com/hfreport.html", body)
if err != nil {
// handle err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}

resp, err := client.Do(req)
if err != nil {
// handle err
}
defer resp.Body.Close()

关于curl - 来自 cURL 和 Golang POST 的不同响应 - 不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42185635/

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