Go HTTP客户端不返回cookies

huangapple go评论111阅读模式
英文:

Go HTTP Client not returning cookies

问题

我正在使用Go的HTTP客户端进行GET请求,该客户端已经初始化了一个cookiejar,但是响应的cookie数组为空。有人知道我做错了什么吗?

  1. jar, err := cookiejar.New(nil)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. s.http_client = &http.Client{Jar: jar}
  6. resp, _ := s.http_client.Get(s.url)
  7. 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?

  1. jar, err := cookiejar.New(nil)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. s.http_client = &http.Client{Jar: jar}
  6. 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跟随重定向”中所示那样使用它:

  1. jar, err := cookiejar.New(&options)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. client := http.Client{Jar: jar} // <============
  6. resp, err := client.Get("http://dubbelboer.com/302cookie.php")
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. data, err := ioutil.ReadAll(resp.Body)
  11. resp.Body.Close()

(在Go1.1中引入,就像这个答案中所述)

一个http.Client结构体有:

  1. // Jar specifies the cookie jar.
  2. // If Jar is nil, cookies are not sent in requests and ignored
  3. // in responses.
  4. Jar CookieJar

3of3所提到的,你不需要一个cookiejar来**获取cookie**:

  1. for _, cookie := range r.Cookies() {
  2. fmt.Fprint(w, cookie.Name)
  3. }

在读取完整个响应体之后,检查cookiejar是否仍然为空。

英文:

You create a cookiejar, and you can use it as seen in "how to follow location with cookie":

  1. jar, err := cookiejar.New(&amp;options)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. client := http.Client{Jar: jar} // &lt;============
  6. resp, err := client.Get(&quot;http://dubbelboer.com/302cookie.php&quot;)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. data, err := ioutil.ReadAll(resp.Body)
  11. resp.Body.Close()

(introduced with Go1.1 as in this answer)

An http.Client struct has:

  1. // Jar specifies the cookie jar.
  2. // If Jar is nil, cookies are not sent in requests and ignored
  3. // in responses.
  4. Jar CookieJar

As 3of3 mentions, you don't need a cookiejar to fetch a cookie:

  1. for _, cookie := range r.Cookies() {
  2. fmt.Fprint(w, cookie.Name)
  3. }

Check if the cookiejar is still empty after having read the full response body.

huangapple
  • 本文由 发表于 2014年11月30日 04:27:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/27206746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定