有人可以用以下代码帮助我吗?我有一个功能,尝试使用URL“ https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/all.json”从网站上获取一些数据。
但是由于某些原因,我总是会收到System.Net.WebException“'基础连接已关闭:接收时发生意外错误。'
我也可以使用URL“ https://www.nseindia.com/api/market-data-pre-open?key=ALL”获得相同的数据,但是在这里,我再次使用C#.net代码获得相同的WebException。
以下是我的代码:
public static string GetNSEData()
{
//*********get the json file using httpRequest ***********
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/all.json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string file;
var response = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
file = sr.ReadToEnd();
}
return file;
}
我尝试了HTTPWebRequest的不同变体以及不同的参数,但没有成功。在每种情况下,我要么遇到相同的异常,要么“远程服务器返回错误:(403)禁止。”
以下是我尝试过的选项:
我们非常感谢您的帮助...
答案 0 :(得分:1)
您只需要摆脱httpWebRequest.UserAgent,然后一切似乎都可以正常工作,因为Http请求不需要它。
public static string GetNSEData()
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/all.json");
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
string file;
var response = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
file = sr.ReadToEnd();
}
return file;
}