2016-08-14 176 views
0

我試圖從利用netscape HTTP cookie文件登錄的舊網站獲取信息。這裏是我的捲曲請求:用曲奇向Golang發出HTTP請求

// 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性病HTTP包?

+0

使用的['http.CookieJar'](http://golang.org/pkg/net/http/#Cookie Jar)在多個請求之間管理Cookie。有關介紹,請參閱相關問題[cookie和cookiejar有何區別?](http://stackoverflow.com/questions/31270461/what-is-the-difference-between-cookie-and-cookiejar) – icza

回答

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(S)餅乾:

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, 
} 
+0

很好的解釋,謝謝! – asing