登录
首页 >  Golang >  Go问答

golang 请求时使用cookie

来源:SegmentFault

时间:2023-01-27 18:29:31 311浏览 收藏

本篇文章向大家介绍《golang 请求时使用cookie》,主要包括go、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

正确答案

可以使用 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加入
}

今天带大家了解了go、Cookie的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表