You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言HTTP POST请求无法获取响应Cookie问题求助

问题描述

我发送POST请求尝试从响应中获取包含登录令牌的Cookie,在Curl和Postman中执行相同请求均能成功获取该Cookie,但在Go语言代码中无法实现。

Go代码示例
func loginAndGetToken() {
    client := &http.Client{}
    postData := strings.NewReader("name=name&password=password&action=login")
    req, err := http.NewRequest("POST", "http://localhost/index.php", postData)
    if err != nil {
        fmt.Printf("Error creating request: %s\n", err)
        return
    }
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error executing request: %s\n", err)
        return
    }
    defer resp.Body.Close()

    // 读取响应体
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %s\n", err)
        return
    }
    bodyString := string(bodyBytes)

    fmt.Println("Status code:", resp.StatusCode)
    fmt.Println("Response Headers:", resp.Header)
    fmt.Println("Response Body:", bodyString)
    fmt.Println("Cookies:", resp.Cookies())
    fmt.Println("Cookies:", resp)

    cookies := resp.Cookies()
    
    if len(cookies) > 0 {
        authDetails.PHPPASSSAFE = cookies[0].Value
        fmt.Println("Cookie value:", authDetails.PHPPASSSAFE)
    } else {
        fmt.Println("No cookie found in response header.")
    }
}
执行结果

请求返回状态码200,能获取到响应头信息,但Cookie数组为空:

Cookies: []
更新:可成功获取Cookie的Curl请求示例
curl -bPOST -d "name=user&password=password&action=login" http://localhost/index.php 

 curl -i -X POST \
  http://localhost/index.php \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'name=name&password=password&action=login'
HTTP/1.1 302 Found
Date: Wed, 21 Feb 2024 15:15:38 GMT
Server: Apache/2.4.54 (Debian)
X-Powered-By: PHP/7.4.33
Set-Cookie: phpPassSafe= tokenValue; expires=Wed, 21-Feb-2024 15:45:38 GMT; Max-Age=1800

内容的提问来源于stack exchange,提问作者Lennart Zinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:52:51