首页 > 解决方案 > 具有多个 URL 的 HttpWebResponse 导致错误

问题描述

我有这个代码:

public class WebDataDownloader
{
    public string GetJSONFromURL(string url)
    {
         string file = string.empty;
         //*********get the json file using httpRequest ***********

         try
         {
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            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.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            using (var response = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    file = sr.ReadToEnd();
                }
            }
        }
        catch(Exception exp)
        {
            Debug.WriteLine(exp.Message);
        }

        return file;
    }
}

现在我多次调用这个方法来获取 JSON 并解析它。如下所示:

public class MyClass
{
    WebDataDownloader myWebClient = new WebDataDownloader();
    string Json1 = myWebClient.GetJSONFromURL(@"https://www.nseindia.com/api/market-data-pre-open?key=ALL");

    //Do some action on this data

    string Json2 = myWebClient.GetJSONFromURL(@"https://www.nseindia.com/api/equity-stock?index=fu_nifty50");

    //Do some action on this data

    string Json3 = myWebClient.GetJSONFromURL(@"https://www.nseindia.com/api/liveEquity-derivatives?index=nifty_bank_fut");

    //Do some action on this data
}

但是,问题是,第一次调用 (Json1) 使用

response = (HttpWebResponse)httpWebRequest.GetResponse()

工作正常,但第 2 次和第 3 次调用在同一实例中不起作用。

有人可以帮我解决这个问题吗...

提前致谢。

标签: c#httpwebrequesthttpwebresponsesystem.net.webexception

解决方案


推荐阅读