HttpWebRequest & HttpWebResponse issues

有些话、适合烂在心里 提交于 2019-12-11 02:14:57

问题


I have tried to connect to a server with HttpWebRequest & HttpWebResponse and it works fine, but I got another problem I want to know when the server have been time out or disconnected, suppose something happened to my connection and I got disconnected I want to know how can I understand this in the following code:

string uri = @"myUrl";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.Credentials = new NetworkCredential(User, Pass);
        ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
        byte[] buf = new byte[10000];
        int count = -1;
        String read = "";
        HttpWebResponse response;
        //MessageBox.Show("OK");
        //response = (HttpWebResponse)request.GetResponse();
        //count = response.GetResponseStream().Read(buf, 0, buf.Length);
        //read = Encoding.UTF8.GetString(buf, 0, count);
        //MessageBox.Show(read + "SALAM");
        //while (true)
        //{
        response = (HttpWebResponse)request.GetResponse();
        //while (true)
        //{
        do
        {
            count = response.GetResponseStream().Read(buf, 0, buf.Length);
            read += Encoding.UTF8.GetString(buf, 0, count);
        } while (response.GetResponseStream().CanRead && count != 0);

        if (read != "")
        {
            // MessageBox.Show(read);
            XDocument xdoc = XDocument.Parse(read);

            //Filter EventXML
            var lv1s = from lv1 in xdoc.Descendants("event")
                       select new
                       {
                           Event_id = lv1.Attribute("id").Value,
                           Header = lv1.Attribute("name").Value,
                           Children = lv1.Descendants("argument")
                       };
            List<event_details> event_detail = new List<event_details>();


            foreach (var lv1 in lv1s)
            {
                if (lv1.Event_id == event_id)
                    foreach (var lv2 in lv1.Children)
                    {
                        event_details x = new event_details();
                        x.type = lv2.Attribute("type").Value;
                        x.value = lv2.Attribute("value").Value;
                        event_detail.Add(x);
                    }
            }
            //inja chun ke daram rooye MsgDGV ke ye k Datagridview minevisam bayad hatman az Invoke estefade konam
            // ta kharabkari nashe:P:D
            Point detail_point = new Point();
            detail_point.X = MsgDGV.Width / 2 + (this.Width - MsgDGV.Width) / 2;
            detail_point.Y = MsgDGV.Height / 2 + (this.Height - MsgDGV.Height) / 2;
            Details detail = new Details(event_detail, timestamp, EVENT, detail_point);
            detail.ShowDialog();
            event_details.Abort();
        }

回答1:


When the Request.GetResponse() method call Times Out you need to catch the WebException that is thrown when the HttpWebRequest.GetResponse method is called. There are four Exceptions that the GetResponse() method can throw so you need to either check the type of Exception thrown or catch the specific exception Type you require ie: Catch (WebException ex) { }.

Note you can Get and Set the WebRequest.Timeout property as required.

// Set the 'Timeout' property in Milliseconds.
request.Timeout = 10000;

In your code you would wrap the HttpWebRequest.GetResponse() method call and all code relating to the data exposed by the GetResponse() call in a Try-Catch block. You should also be taking advantage of the fact that WebResponse implements IDisposable and use the using syntax to manage object scope and lifetime so you are not left with references to objects no longer required or in scope.

try 
{
    using (WebResponse response = request.GetResponse())
    {
            // ALL OTHER CODE
    }
}
catch (Exception ex)
{
    // Handle Exception 
}



回答2:


Actually I found the way!!, The two answers above are working fine when you are disconnected from the internet or there is some problem with your connection, and it throws an exception and with the ways specified above, we can solve it, but when you are connected and in the middle of that you got disconnected the situation changed. Since you were connected, and you reach the:

response.GetResponseStream().Read(buf, 0, buf.Length);

Then it will stuck in this function then for the read you should specify a timeout so C# got this:

response.GetResponseStream().ReadTimeout = 1000;

so before the read you should specify a timeout and then everything works fine;




回答3:


You can catch WebException to see if error has occured during request execution or time-out period for the request expired:

try 
{
  using(var response = (HttpWebResponse)request.GetResponse())
  {

  }
}
catch(WebException e)
{
   //timeout or error during execution
}

Also you may need check the status of response to be equal 200:

if(resp.StatusCode == 200)
{
  //code
}

More details about HttpRequest you can find here



来源:https://stackoverflow.com/questions/9140289/httpwebrequest-httpwebresponse-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!