HTTPWebRequest 403 Forbidden

时间:2012-07-31 18:46:28

标签: c# httpwebrequest basic-authentication httpwebresponse

我正在尝试向服务器形成HttpWebRequest。我已经测试了我正在使用的用户名和密码,并且他们使用目标网站上的登录表单进行了正确的身份验证。

我查了一下并阅读了有关HttpWebRequest的关于403的所有其他帖子,我更新了我的代码以获得有效的useragent,Accept字段和ContentType。遗漏前三个属性之一似乎是人们最常犯的错误。

我的代码如下,并打印“响应创建远程服务器返回错误:(403)禁止。”

{
    HttpWebRequest request = buildRequest(url);        
    print("Response Created");
    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            //Do stuff with the response
        }
    }
    catch (Exception ex)
    {
        print(ex.Message);
    }
    Done.Visible = true;
}

private HttpWebRequest buildRequest(String url)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    //I also tried authenticating in the header with no luck.
    //byte[] authBytes = Encoding.UTF8.GetBytes("username:password".ToCharArray());
    //req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);
    req.Method = "GET";
    req.Credentials = new NetworkCredential("username","password");
    req.UserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-us) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27";
    req.PreAuthenticate = true;
    req.Accept = "application/json";
    req.ContentType = "application/json; charset=utf-8";
    req.KeepAlive = true;
    return req;
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

使用System.Net.CookieContainer在后​​续通话中接收和设置Cookie。 CookieContainer属性在不同请求中是有状态的。

Here是MSDN文档。

public SomeClass 
{
    var _cookies = new CookieContainer();

    private HttpWebRequest buildRequest(String url)  
    {  
       HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);  
       req.CookieContainer = _cookies;
       // omitted rest of code
    }

}

答案 1 :(得分:0)

您确定该网站在登录时不使用POST方法吗?如果没有,那就忽略这个答案。

如果网站在提交数据时使用POST方法,您需要在提交数据之前将数据附加到请求的末尾(您可以使用Fiddler轻松检查):

string postDataString = "foo1=bar1&foo2=bar2&foo3=bar3";
//Use whatever encoding is appropriate for the submission
byte[] postData = Encoding.ASCII.GetBytes(postDataString);


//When building your request, set the ContentLength property and append the data
req.ContentLength = postData.Length;

using (Stream dataStream = req.GetRequestStream())
{
    dataStream.Write(postData, 0, postData.Length);
}