Go语言如何通过之前获取的cookie发起获取cookie值的请求和发起新的请求?

Go语言如何通过之前获取的cookie发起获取cookie值的请求和发起新的请求


cookie这里的第一个帖子请求是在表单中生成一个变量[SID=pcmPXXx+fidX1xxxX1cuK; Path=/; HttpOnly; SameSite=Strict]" 


但我无法将此 cookie 发送到另一个发布请求(出现错误)。


带有注释的示例 go 文件


package main


import (

  "fmt"

  "log"

  "strings"

  "net/http"

  "io/ioutil"

  "net/http/cookiejar"

)


var client http.Client

func init() {

    jar, err := cookiejar.New(nil)

    if err != nil {

        log.Fatalf("Got error while creating cookie jar %s", err.Error())

    }

    client = http.Client{

        Jar: jar,

    }

}


func main() {


  urlx := "http://localhost:8080/api/v2/auth/login"

  methodx := "POST"


  payloadx := strings.NewReader(`username=admin&password=strongadmin`)


  client := &http.Client {

  }

  reqx, err := http.NewRequest(methodx, urlx, payloadx)


  if err != nil {

    fmt.Println(err)

    return

  }

  reqx.Header.Add("Referer", "http://localhost:8080/")

  reqx.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36")

  reqx.Header.Add("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")


  resx, err := client.Do(reqx)

  if err != nil {

    fmt.Println(err)

    return

  }

  defer resx.Body.Close()



  cookie := resx.Cookies()

  fmt.Println(cookie)


  bodyx, err := ioutil.ReadAll(resx.Body)

  if err != nil {

    fmt.Println(err)

    return

  }

  fmt.Println(string(bodyx))







  //second request start here 

// this var cookies is a dummy cookie that i manually written,

// i need to replace the below variable 'cookies' to previously obtained variable 'cookie' without error






  cookies := &http.Cookie{

      Name: "SID",

      Value: "PW16gD0Ja0OqixXeqpQle1WC/OK19tj+",

      MaxAge: 300,

  }

  url := "http://localhost:8080/api/changes"

  method := "POST"


  payload := strings.NewReader(`json=%7B%data=valuex%22%3A%22300%22%7D`)


  clientx := &http.Client {

  }

  req, err := http.NewRequest(method, url, payload)


  if err != nil {

    fmt.Println(err)

    return

  }


慕虎7371278
浏览 83回答 1
1回答

湖上湖

在第一个请求中,您得到的 cookie 是:cookie := resx.Cookies()这是 Cookie 结构的切片[]*http.Cookie然后,如果您想在下一个请求中使用它们,请循环遍历它们并添加:for _, c := range cookie {   req.AddCookie(c) }检查这个例子
打开App,查看更多内容
随时随地看视频慕课网APP