2015-09-29 97 views
0

當我運行這個python腳本爲什麼Response.Cookies是空的?

import requests 

main_page_request = requests.get("http://carkit.kg/") 
cookie = main_page_request.cookies.get("csrftoken", "") 

我得到正確的結果,但是當我運行在C#這樣的代碼:

string url = @"http://carkit.kg"; 

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

Debug.Log(response.Cookies["csrftoken"]); // prints "Null" 

它說,response.Cookies是空的。問題是什麼?

+2

'response.Cookies ['mycookie'])'不會編譯。小心顯示你的實際代碼? – CodeCaster

+1

在Python中,您正在從請求中讀取Cookie,並從C#中響應。更新了代碼 – niksofteng

+0

。當我嘗試使用request.Cookies時,它說:'HttpWebRequest'不包含'Cookies'的定義。 –

回答

2

您必須向請求添加一個cookie容器。然後它返回cookie:

CookieContainer c = new CookieContainer(); 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.CookieContainer = c; 

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

Console.WriteLine(response.Cookies["csrftoken"]); 
// prints "csrftoken=E1iRIi7cQvxvJcnSgOgaEP3XPxTHRUfT" 
+0

是的,謝謝! –