golang 请求时使用cookie

使用golang自定义函数login模拟登陆后,会获得一个response中cookie,怎么用这个cookie继续访问其他页面

func main(){
    resp,err := login()
    if err != nil {
        print(err)
    }
    //for _,i := range resp.Cookies(){
    //    fmt.Println(i)
    //}
    url := "xxxxx"
    client := &http.Client{}
    req,err := http.NewRequest("POST",url,nil)
    if err != nil {
        print(err)
    }
    req.Header.Set("Cookie",resp.Cookies())  //数组报错
    req.Header.Set("Pragma","no-cache")
    req.Header.Set("Accept-Encoding","gzip, deflate, sdch")
    req.Header.Set("Accept-Language","zh-CN,zh;q=0.8")
    req.Header.Set("Upgrade-Insecure-Requests","1")
    req.Header.Set("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36")
    req.Header.Set("Accept","text/javascript, text/html, application/xml, text/xml, */*")
    req.Header.Set("Connection","keep-alive")
    req.Header.Set("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")
    req.Header.Set("Cache-Control","no-cache")

    resp2, err := client.Do(req)
    if err != nil {
        print(err)
    }

    body, err := ioutil.ReadAll(resp2.Body)
    fmt.Println(string(body))
}

func login() (*http.Response, error) {
    url := "xxxxx"
    client := &http.Client{}
    req,err := http.NewRequest("POST",url,strings.NewReader("name=cjb"))
    if err != nil {
        print(err)
    }
    req.Header.Set("Pragma","no-cache")
    req.Header.Set("Accept-Encoding","gzip, deflate, sdch")
    req.Header.Set("Accept-Language","zh-CN,zh;q=0.8")
    req.Header.Set("Upgrade-Insecure-Requests","1")
    req.Header.Set("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36")
    req.Header.Set("Accept","text/javascript, text/html, application/xml, text/xml, */*")
    req.Header.Set("Connection","keep-alive")
    req.Header.Set("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")
    req.Header.Set("Cache-Control","no-cache")
    //用户登陆设置...
    
    //请求,获取cookie
    resp, err := client.Do(req)

    //defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        print(err)
    }
    fmt.Println(string(body))
    return resp,nil
阅读 21.7k
3 个回答

可以使用 CookieJar:

import "net/http/cookiejar"

func main() {
    var client http.Client
    jar, err := cookiejar.New(nil)
    if err != nil {
        panic(err)
    }
    client.Jar = jar

    client.Post(...) // 在这里登陆
    client.Get()     // 后续请求client会自动将cookie加入
}

req.Header.Set 这个方法是这样的

func (h Header) Set(key, value string)

2个参数都是string类型。
关于 golang cookie 的使用, 你可以参考下:http://studygolang.com/articles/5905

在你这里应该是

for _, c := range resp.Cookies() {
    req.AddCookie(c)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏