英文:
Go HTTP Client not returning cookies
问题
我正在使用Go的HTTP客户端进行GET请求,该客户端已经初始化了一个cookiejar,但是响应的cookie数组为空。有人知道我做错了什么吗?
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
s.http_client = &http.Client{Jar: jar}
resp, _ := s.http_client.Get(s.url)
fmt.Println(resp.Cookies())
fmt.Println(resp.Cookies())
返回一个空数组,尽管我可以在Firefox中看到返回的cookie。
英文:
I am using go http client to make get requests and the client has been initialised with a cookiejar however the response cookie array is empty. Has anyone got any idea what I am doing wrong?
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
s.http_client = &http.Client{Jar: jar}
resp, _ := s.http_client.Get(s.url)
fmt.Println(resp.Cookies())
returns an empty array although I can see cookies returned in firefox.
答案1
得分: 5
你可以创建一个cookiejar
,并且可以像在“如何使用cookie跟随重定向”中所示那样使用它:
jar, err := cookiejar.New(&options)
if err != nil {
log.Fatal(err)
}
client := http.Client{Jar: jar} // <============
resp, err := client.Get("http://dubbelboer.com/302cookie.php")
if err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
(在Go1.1中引入,就像这个答案中所述)
一个http.Client
结构体有:
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar CookieJar
如3of3所提到的,你不需要一个cookiejar来**获取cookie**:
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
在读取完整个响应体之后,检查cookiejar是否仍然为空。
英文:
You create a cookiejar
, and you can use it as seen in "how to follow location with cookie":
jar, err := cookiejar.New(&options)
if err != nil {
log.Fatal(err)
}
client := http.Client{Jar: jar} // <============
resp, err := client.Get("http://dubbelboer.com/302cookie.php")
if err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
(introduced with Go1.1 as in this answer)
An http.Client
struct has:
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar CookieJar
As 3of3 mentions, you don't need a cookiejar to fetch a cookie:
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
Check if the cookiejar is still empty after having read the full response body.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论