当我运行这个python脚本时
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"
它说响应.Cookies是空的。有什么问题?
答案 0 :(得分: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"