Go HTTP客户端不返回cookies

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

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(&amp;options)
if err != nil {
    log.Fatal(err)
}
client := http.Client{Jar: jar}  // &lt;============
resp, err := client.Get(&quot;http://dubbelboer.com/302cookie.php&quot;)
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.

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:

确定