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: []
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
相关产品推荐
相关产品推荐

