2015-09-29 38 views
1

我有以下代码:403错误在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如果密码不正确,carkit.kg/game在其他情况下。

最后的请求具有相同的URL作为第一个,但我得到的第二个403错误。

有使我想能够做的C#代码工作在Python这样的代码:

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 

回答

2

我的猜测是,你没有进入正确的格式的凭证信息。我会用一个CredentialCache,并设置预认证=真 下面是该代码:

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?

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

loginRequest.ContentLength = data.Length;

+0

所以,我应该插入我的代码是什么? –

+0

我试过你的代码(问题更新)。 ?不过,这并不帮助((请求超时 –

+0

请问你的网络服务器已经基本或摘要式身份验证这听起来像你的Web服务器而不是你的代码 –