【问题标题】:Curl with cookies to Golang HTTP request使用 cookie 卷曲到 Golang HTTP 请求
【发布时间】:2016-12-20 17:58:09
【问题描述】:

我正在尝试从一个使用 netscape HTTP cookie 文件登录的旧站点获取信息。这是我的 curl 请求:

// Do login request and get cookie
curl -c cookies -X POST -i -v https://foobar.com/login

// Use generated cookie file to get more data about the user
curl -b cookies -i -v https://foobar.com/data

在 PHP 中,您可以执行以下操作:

// Do login request and get cookie
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://foobar/login');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, './cookies');
curl_setopt($ch, CURLOPT_COOKIEFILE, './cookies');  
$user = curl_exec($ch);

// Use generated cookie file to get data about the user 
curl_setopt($ch, CURLOPT_URL, 'https://foobar/login');
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, './cookies');
curl_setopt($ch, CURLOPT_COOKIEFILE, './cookies');  
$data = curl_exec($ch);

有没有办法在 Go 中使用 std http 包来做到这一点?

【问题讨论】:

标签: php curl cookies go


【解决方案1】:

保存 cookie:

// do whatever is needed to login and get the cookie
response, err := http.PostForm("http://localhost:8080/login", url.Values{"username": {"foo"}, "password": {"bar"}})
if err != nil {
    log.Fatal(err)
}

var savedCookie *http.Cookie

for _, cookie := range response.Cookies() {
    if cookie.Name == "secret" {
        savedCookie = cookie
    }
}

获得 cookie 后,您可以构建另一个请求并添加 cookie:

client := http.Client{}
request, err := http.NewRequest("GET", "http://localhost:8080/protected", nil)
if err != nil {
    log.Fatal(err)
}

request.AddCookie(savedCookie)
response, err := client.Do(request)
if err != nil {
    log.Fatal(err)
}

如果您有多个 Cookie,您可以使用 CookieJar 并直接在客户端中设置它们:

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

【讨论】:

    猜你喜欢
    • 2019-03-31
    • 2016-12-06
    • 2021-05-31
    • 1970-01-01
    • 2018-07-08
    • 2017-04-13
    • 2018-09-20
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多