我正在尝试从使用netscape HTTP Cookie文件登录的旧网站获取信息。这是我的卷曲请求:
// 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包来执行此操作?
答案 0 :(得分:2)
要保存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,
}