Unity3D C# 中的 403 错误

403 error in Unity3D C#

我有以下代码:

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。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

我猜你没有以正确的格式输入凭据信息。我会使用 CredentialCache 并设置 PreAuthenticate=true 这是代码:

var cache = new CredentialCache();
cache.Add(new Uri(uri), "Digest", new NetworkCredential(username, password));
httpRequest.Credentials = cache;
httpRequest.PreAuthenticate = true;

要修复 411 错误,请尝试以下操作: Why I get 411 Length required error?

为什么要在 data.length 上加 1?我会尝试

loginRequest.ContentLength = data.Length;