我想请您帮助我快速编写以下代码,因为我总是收到“403 FORBIDDEN”。
HttpWebRequest pozadavek = (HttpWebRequest)WebRequest.Create("LINK THAT ASKS FOR AUTHLOGIN"); //https
System.IO.StreamReader stream = null;
System.String result = null;
public Form1()
{
InitializeComponent();
pozadavek.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
pozadavek.Credentials = new NetworkCredential("NAME", "PASS");
pozadavek.PreAuthenticate = true;
}
private void Form1_Load(object sender, EventArgs e)
{
WebResponse webresponse = pozadavek.GetResponse(); //throws an exception:403 forbidden
stream = new System.IO.StreamReader(webresponse.GetResponseStream());
result = stream.ReadToEnd();
this.webBrowser1.DocumentText = result;
}
最佳答案
您尝试打开的网站需要基本身份验证。最重要的是,您需要在您的请求中包含以 base64 编码的用户名/密码。幸运的是,.Net 可以为您做到这一点。像这样构建您的请求:
var credCache = new CredentialCache();
credCache.Add(new Uri("https://is.vsfs.cz/auth"), "Basic",
new NetworkCredential("user", "pwd"));
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = credCache;
Here's one article更详细地解释 .Net 中如何处理各种身份验证方案。
关于C# HttpWebRequest - 预验证 : Still returns 401 forbidden (HTTPS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2220297/