正确处理WebRequests

时间:2017-02-07 09:38:34

标签: c# json visual-studio

我有一个带有.JSON文件的动态页面,我每隔x秒使用我的C#程序访问它,以确定是否有某些内容被更改。只要我有互联网连接,一切都完美无缺,如果由于某种原因我失去它,那么我的程序崩溃,因为ex.Response是空的。我想知道是否有更好的方法来处理以下代码:

void Function(){
while(true){
 jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl)); 
//SOME THINGS I DO with the data above here

Thread.Sleep(5000);
}}



     string GET(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        try
        {
            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
        catch (WebException ex)
        {
            WebResponse errorResponse = ex.Response;
            if (ex.Response != null) { 
            using (Stream responseStream = errorResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                String errorText = reader.ReadToEnd();
                // log errorText
            }
        }
            throw;
        }
    }

也许我应该先ping它,看看我是否得到了回复,然后才执行WebRequest功能?

编辑:

添加此

  public bool getResponse(string URL)
        {
            try
            {
                WebClient wc = new WebClient();
                string HTMLSource = wc.DownloadString(URL);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

并将其用作

void Function(){
while(true){
        if (!getResponse(jsonUrl))
                {
                    return;
                }
 jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl)); 
//SOME THINGS I DO with the data above here

Thread.Sleep(5000);
}}

我的C#应用​​程序稍稍等待,然后正常退出。为什么呢?

该程序&#39; [10476] Kiosk2.vshost.exe&#39;已退出代码0(0x0)。

1 个答案:

答案 0 :(得分:0)

好吧,这似乎对我来说很好。

  public void Update() //CALLED IT void FUNCTION earlier
        {

            while (true)
            {
                while (getResponse(jsonUrl))
                {


                    jList = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<jsonList>(GET(jsonUrl));

 //I DO SOME STUFF HERE
 //INTERESTING STUFF


                    Thread.Sleep(5000);

                }

            }


        }

秒功能:

public bool getResponse(string URL)
    {
        try
        {
            WebClient wc = new WebClient();
            string HTMLSource = wc.DownloadString(URL);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }