doy2255 2014-11-29 20:27
浏览 141
已采纳

Go HTTP客户端不返回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条回答 默认 最新

  • dsijovl015728613 2014-11-29 20:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?