C# HttpWebRequest远程服务器返回错误:(401)未经授权
我正在尝试向一个不需要任何凭据的网站发出web请求 我把邮递员工具和饼干一起使用,效果很好。我从chrome浏览器中获取cookie 。但是,我尝试设置cookie、TLS和使用默认凭据,但没有任何帮助 主网站:在这个网站上,我转到开发者工具并复制cookie值 Web请求URL: 代码:C# HttpWebRequest远程服务器返回错误:(401)未经授权,c#,httpwebrequest,C#,Httpwebrequest,我正在尝试向一个不需要任何凭据的网站发出web请求 我把邮递员工具和饼干一起使用,效果很好。我从chrome浏览器中获取cookie 。但是,我尝试设置cookie、TLS和使用默认凭据,但没有任何帮助 主网站:在这个网站上,我转到开发者工具并复制cookie值 Web请求URL: 代码: 请帮助。我为它编写了代码,它可以正常工作@亚罗斯拉夫门什科夫感谢你的帮助。但是,无法运行该代码。它缺少依赖项。如果您上传完整的解决方案,那就太好了。特别是,它缺少cookies对象和CatalogSuppor
请帮助。我为它编写了代码,它可以正常工作@亚罗斯拉夫门什科夫感谢你的帮助。但是,无法运行该代码。它缺少依赖项。如果您上传完整的解决方案,那就太好了。特别是,它缺少cookies对象和CatalogSupportLibrary.Requests的命名空间。请上传整个解决方案。谢谢你!CookieContainer-使用System.Net;CatalogSupportLibrary.Requests位于同一个存储库@YaroslavMenshikov,感谢您的回复。当我检查Ajax请求时,我可以看到一个非常大的cookie,但您设法添加了4个cookie值(bm_mi、ak_bmsc、bm_sv、nseappid、nsit)。如果您能告诉我您是如何识别这些不同的cookies的,那将非常有帮助。您可以使用Fiddler或在您的浏览器中查看所有cookies。
void DOSomething()
{
try
{
string html = string.Empty;
string url = @"https://www.nseindia.com/api/option-chain-equities?symbol=APOLLOHOSP";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
string cook = System.Net.WebUtility.UrlEncode(txtCookie.Text.Trim());
Uri target = new Uri(url);
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.UseDefaultCredentials = true;
request.PreAuthenticate = true;
request.Credentials = CredentialCache.DefaultCredentials;
request.CookieContainer.Add(new System.Net.Cookie("cookie",cook) { Domain = "nseindia.com" });
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
Console.WriteLine(html);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}