在执行 HTTP Get 请求时,我收到以下错误:
2015/08/30 16:42:09 Get https://en.wikipedia.org/wiki/List_of_S%26P_500_companies:
stopped after 10 redirects
在下面的代码中:
package main
import (
"net/http"
"log"
)
func main() {
response, err := http.Get("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
if err != nil {
log.Fatal(err)
}
}
根据文档我知道,
// Get issues a GET to the specified URL. If the response is one of
// the following redirect codes, Get follows the redirect, up to a
// maximum of 10 redirects:
//
// 301 (Moved Permanently)
// 302 (Found)
// 303 (See Other)
// 307 (Temporary Redirect)
//
// An error is returned if there were too many redirects or if there
// was an HTTP protocol error. A non-2xx response doesn't cause an
// error.
我希望有人知道在这种情况下的解决方案。这个简单的 url 会导致十多个重定向,这似乎很奇怪。让我觉得幕后可能还有更多事情要做。
谢谢。
最佳答案
正如其他人所指出的,您应该首先考虑一下为什么会遇到这么多 HTTP 重定向。 Go 在 10 次重定向时停止的默认策略是合理的。超过 10 个重定向可能意味着您处于重定向循环中。这可能是在您的代码之外引起的。它可能是由您的网络配置、您与网站之间的代理服务器等引起的。
就是说,如果您确实需要更改默认策略,则无需像有人建议的那样诉诸于编辑 net/http 源。
要更改重定向的默认处理方式,您需要创建一个客户端并设置 CheckRedirect。
供您引用: http://golang.org/pkg/net/http/#Client
// If CheckRedirect is nil, the Client uses its default policy,
// which is to stop after 10 consecutive requests.
CheckRedirect func(req *Request, via []*Request) error
关于redirect - 维基百科网址在 10 次重定向错误 GoLang 后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302777/