我有一个python脚本:
import requests
main_page_request = requests.get("http://carkit.kg/")
csrf_cookie = main_page_request.cookies.get("csrftoken", "")
r = requests.post("http://carkit.kg/", data={u'username': u'admin', u'password': u'admin', 'csrfmiddlewaretoken': csrf_cookie }, cookies={'csrftoken': csrf_cookie})
print r.url
carkit.kg/ - 是django app中的登录网址。如果身份验证成功,脚本将打印一个URL,而在其他情我试图用C#(Unity3D游戏)重写这个脚本:
//get token
string url = "http://carkit.kg";
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(url);
tokenRequest.CookieContainer = new CookieContainer();
HttpWebResponse tokenResponse = (HttpWebResponse)tokenRequest.GetResponse();
String token = tokenResponse.Cookies["csrftoken"].ToString().Split('=')[1];
//login
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(url);
loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token, "/", "carkit.kg"));
String postData = "username=" + tempEmail;
postData += "&password=" + tempPass;
postData += "&csrfmiddlewaretoken=" + token;
byte[] data = Encoding.ASCII.GetBytes(postData);
loginRequest.ContentLength = data.Length + 1;
Debug.Log(data.Length);
loginRequest.Timeout = 3000;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(tempEmail + ":" + tempPass));
loginRequest.Headers.Add("Authorization", "Basic " + encoded);
loginRequest.GetRequestStream().Write(data, 0, data.Length);
loginRequest.PreAuthenticate=true;
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
但我收到错误411或超时请求。如何在C#代码中获得与python中相同的结果?