cURL 和 Golang POST 的不同响应 - 无法理解为什么

2024-03-02

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

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

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

我已经编写了等效的 go 代码,并且还尝试使用名为卷曲即走 https://mholt.github.io/curl-to-go/,它为上面生成以下 go 代码curl要求:

 // 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 to the curl命令复制其所有标头,因此我通过 go 代码添加了以下标头:

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 one.

关于如何获得相同的任何想法curl来自 go 的响应?


感谢@u_mulder 为我指出了正确的方向。好像默认走http客户端默认遵循重定向标头,而curl才不是。

这是更新后的代码,它在 go 和 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

cURL 和 Golang POST 的不同响应 - 无法理解为什么 的相关文章

随机推荐