Problems with HttpWebRequest & HttpWebResponse

I tried to connect to the server using HttpWebRequest and HttpWebResponse and it works fine, but I got another problem I want to know when the server was down or disconnected, suppose something happened to my connection and I disconnected ... want to know how can i figure it out 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();
        }

      

+2


source to share


3 answers


I actually found a way !!. The above two answers work fine when you are disconnected from the internet, or there is some problem with your connection and it throws an exception and with the above methods, we can solve this, but when you are connected and in the middle of being disconnected , the situation has changed. Since you were connected and you will achieve:

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

      

Then it will get stuck in that function, then for reading you have to specify a timeout for C # to get this:



response.GetResponseStream().ReadTimeout = 1000;

      

so before reading you have to specify a timeout and then everything will work fine;

+1


source


When the Request.GetResponse () method calls Times Out, you need to catch the WebException that is thrown when HttpWebRequest.GetResponse . There are four exceptions that the GetResponse () method can throw, so you need to either check for the Exception type or load a specific exception. The type you want, for example: Catch (WebException ex) {}.

Note that you can get and set the WebRequest.Timeout property as needed.

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

      



In your code, you would wrap the HttpWebRequest.GetResponse () method call and all the data-related code exposed by the GetResponse () call in Try- Catch . You should also take advantage of the fact that WebResponse implements IDisposable and uses syntax to manipulate the scope and time of an object so that you don't end up with references to objects that are no longer required or in scope.

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

      

+1


source


You can catch WebException

to see if there was an error during the execution of the request or the timeout period for an expired request:

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

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

      

Also you may need to check if the response status is 200:

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

      

You can find more details about HttpRequest here

0


source







All Articles