【发布时间】:2015-09-29 13:09:27
【问题描述】:
我有以下代码:
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
tokenRequest.CookieContainer = new CookieContainer();
string token = "";
using (var response = (HttpWebResponse)tokenRequest.GetResponse()) {
token = response.Cookies["csrftoken"].ToString().Split('=')[1];
}
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("http://carkit.kg");
var cache = new CredentialCache();
cache.Add(new Uri("http://carkit.kg/"), "Basic", new NetworkCredential(tempEmail, tempPass));
loginRequest.Credentials = cache;
loginRequest.PreAuthenticate = true;
loginRequest.Method = "POST";
loginRequest.CookieContainer = new CookieContainer();
loginRequest.CookieContainer.Add(new Cookie("csrftoken", token) {Domain="carkit.kg"});
Debug.Log(token);
byte[] data = Encoding.UTF8.GetBytes("username=" + tempEmail + "&password=" + tempPass + "&csrfmiddlewaretoken=" + token);
//loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.ContentLength = data.Length;
loginRequest.Timeout = 3000;
loginRequest.GetRequestStream().Write(data, 0, data.Length);
Debug.LogWarning(loginRequest.Headers.ToString());
HttpWebResponse authResponse = (HttpWebResponse)loginRequest.GetResponse();
Debug.Log(authResponse.ResponseUri);
如果密码不正确,authResponse.ResponseUri 应该是http://carkit.kg,其他情况下应该是 carkit.kg/game。
最后一个请求的 url 与第一个相同,但第二个请求出现 403 错误。
python 上有一个代码可以完成我希望 C# 代码能够完成的工作:
import urllib2
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
【问题讨论】:
标签: c# post http-request