2015-09-29 37 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服務器而不是你的代碼 –