【问题标题】:System.Net.WebException: 'The underlying connection was closed: An unexpected error occurred on a receive.'System.Net.WebException:“底层连接已关闭:接收时发生意外错误。”
【发布时间】:2020-06-24 19:26:37
【问题描述】:

有人可以帮我写下下面的代码吗?我有一个函数,我试图使用 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) Forbidden。”

以下是我尝试过的选项:

System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive

C# System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send

非常感谢任何帮助...

【问题讨论】:

    标签: c# httpwebrequest system.net.webexception


    【解决方案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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2011-01-25
      • 2014-03-10
      相关资源
      最近更新 更多