所以,我使用net/http包。我正在GETting一个网址,我知道肯定是重定向。它甚至可能在到达最终的URL之前重定向几次。重定向是在后台自动处理的。
有没有一种简单的方法可以找出最终的URL是什么,而不需要在http.Client对象上设置CheckRedirect字段?
我想我应该提一下,我想我想出了一个解决办法,但它有点老套,因为它涉及到使用全局变量并在自定义http.Client上设置CheckRedirect字段。
一定有一种更干净的方法来做这件事。我希望是这样的:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
// Try to GET some URL that redirects. Could be 5 or 6 unseen redirections here.
resp, err := http.Get("http://some-server.com/a/url/that/redirects.html")
if err != nil {
log.Fatalf("http.Get => %v", err.Error())
}
// Find out what URL we ended up at
finalURL := magicFunctionThatTellsMeTheFinalURL(resp)
fmt.Printf("The URL you ended up at is: %v", finalURL)
}
发布于 2013-05-28 14:35:31
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://stackoverflow.com/q/16784419/727643")
if err != nil {
log.Fatalf("http.Get => %v", err.Error())
}
// Your magic function. The Request in the Response is the last URL the
// client tried to access.
finalURL := resp.Request.URL.String()
fmt.Printf("The URL you ended up at is: %v\n", finalURL)
}
输出:
The URL you ended up at is: http://stackoverflow.com/questions/16784419/in-golang-how-to-determine-the-final-url-after-a-series-of-redirects
发布于 2021-06-19 16:00:29
我要补充一点,http.Head
方法应该足以检索最终的URL。从理论上讲,与http.Get
相比,它应该更快,因为服务器应该只发回一个报头:
resp, err := http.Head("http://stackoverflow.com/q/16784419/727643")
...
finalURL := resp.Request.URL.String()
...
https://stackoverflow.com/questions/16784419
复制相似问题