0

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

我检查并阅读了 Stack 上关于 403 涉及 HttpWebRequest 的所有其他帖子,并更新了我的代码以具有有效的用户代理、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;
}

谢谢你的帮助。

4

2 回答 2

0

使用 aSystem.Net.CookieContainer在后续调用中接收和设置 cookie。该CookieContainer属性在不同的请求中是有状态的。

是 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
    }

}
于 2012-07-31T18:50:50.873 回答
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);
}
于 2012-07-31T19:17:16.563 回答