[英]HTTPWebRequest 403 Forbidden
我正在嘗試向服務器形成一個 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;
}
謝謝你的幫助。
使用System.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
}
}
您確定網站在登錄時沒有使用 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.