HttpWebRequest & HttpWebResponse 问题

发布于 2025-01-02 09:46:47 字数 2759 浏览 1 评论 0原文

我尝试使用 HttpWebRequest & 连接到服务器HttpWebResponse 并且它工作正常,但是我遇到了另一个问题,我想知道服务器何时超时或断开连接,假设我的连接发生了一些事情并且我断开了连接,我想知道如何在以下代码中理解这一点:

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();
        }

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();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

じ违心 2025-01-09 09:46:47

当 Request.GetResponse() 方法调用超时时,您需要捕获 WebExceptionHttpWebRequest.GetResponse 方法被调用。 GetResponse() 方法可以抛出四种异常,因此您需要检查抛出的异常类型或捕获您需要的特定异常类型,即:Catch (WebException ex) { }。

请注意,您可以获取和设置 WebRequest.Timeout 所需的属性。

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

在您的代码中,您可以将 HttpWebRequest.GetResponse() 方法调用以及与 GetResponse() 调用公开的数据相关的所有代码包装在 Try-Catch 块。
您还应该利用 WebResponse 实现 IDisposable 并使用 使用语法来管理对象范围和生命周期,这样您就不会留下对不再需要或范围内的对象的引用。

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

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 
}
尴尬癌患者 2025-01-09 09:46:47

实际上我找到了方法!!,当您与互联网断开连接或连接出现问题时,上面的两个答案都可以正常工作,并且它会抛出异常,并且使用上面指定的方法,我们可以解决它,但是当您已连接,但在中间您断开了连接,情况发生了变化。既然你已连接,并且到达:

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

那么它将卡在这个函数中,然后对于读取,你应该指定一个超时,所以 C# 得到了这个:

response.GetResponseStream().ReadTimeout = 1000;

所以在读取之前,你应该指定一个超时,然后一切正常;

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;

稳稳的幸福 2025-01-09 09:46:47

您可以捕获 WebException查看请求执行期间是否发生错误或请求的超时时间已过期:

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

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

此外,您可能需要检查响应的状态是否等于 200:

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

有关 HttpRequest 的更多详细信息,您可以找到 此处

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文