【发布时间】:2012-07-29 14:53:48
【问题描述】:
我正在尝试向服务器发送 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;
}
感谢您的帮助。
【问题讨论】:
标签: c# httpwebrequest basic-authentication httpwebresponse