【问题标题】:403 error in Unity3D C#Unity3D C#中的403错误
【发布时间】: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


    【解决方案1】:

    我的猜测是您没有以正确的格式输入凭据信息。我会使用 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;

    【讨论】:

    • 我试过你的代码(问题已更新)。但它没有帮助((请求超时
    • 您的网络服务器是否有基本或摘要式身份验证?这听起来像是您的网络服务器而不是您的代码的问题
    • 是的,我解决了这个问题:我将 ContentLength 设置为 data.Length+1。我删除“+ 1”,它开始工作。谢谢你。但是现在我在上面的代码(更新)的同一个地方收到 403 错误
    • 是的,这是我已经解释过的身份验证问题。检查您的网络服务器如何进行身份验证 - 基本或摘要 - 进行上述更改
    • 我也试过协商和承载。我试图将域添加到 NetworkCredentials 构造函数。没有任何帮助
    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 2015-03-02
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多