http - 更改 http.Client cookie 值

标签 http go cookies client

我有以下代码可以按预期工作,但是在第一次请求时,我有我想要的 cookie,并且只想在发送另一个请求之前更改 1 个 cookie 的值。到目前为止,我一直很不成功。

jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
  log.Fatal(err)
}

client = &http.Client{
    Jar: jar,
}

firstRequest() // aka login

mainLinkedinURL := "http://www.example.com/"
cookieURL, _ := url.Parse(mainLinkedinURL)
for j, i := range jar.Cookies(cookieURL) {
    if i.Name == "JSESSIONID" {
        jar.Cookies(cookieURL)[j].Value = "Another New Value"
        i.Value = "Another way of setting a new value"
    }
}
secondRequest() // request after changing cookie

这只是从 http.Client 的角度来看,并没有服务器端的 cookie 管理。

最佳答案

要更改 cookie 的值,您需要使用 SetCookies方法。
因为您只需要更改单个 cookie 值,所以您需要这样的东西:

mainLinkedinURL := "http://www.example.com/"
cookieURL, err := url.Parse(mainLinkedinURL)
if err != nil {
    // handle error properly
}
cookies := jar.Cookies(cookieURL)
for _, cookie := range cookies {
    // note: if there is no cookie with such a name 
    // then a new value would not appear, please pay attention to this
    if cookie.Name == "JSESSIONID" {
        cookie.Value = "Another New Value"
        break
    }
}
jar.SetCookies(cookieURL, cookies)

关于http - 更改 http.Client cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49599927/

相关文章:

php - 我是否在登录系统中使用 cookie 或 session 登录?

当前用户与 ID 的 REST 端点

html - 为什么 html 转义 >159?

go - 从 go channel 流中读取

arrays - Golang 模板 : how to define array in a variable?

cookies - 无法在 Laravel 4 中设置 cookie

php - 在没有 cURL 的情况下在 PHP 中调用 API

java - 将证书添加到 Java 信任库和 Sslhandshake

go - 在 gcloud go sdk for cloudresourcemanager 中使用上下文

.Net Core 2.1 与 IdentityServer4 Cookie 和基于 API JWT 的同一应用程序身份验证