HttpWebRequest超时处理 [英] HttpWebRequest timeout handling

查看:93
本文介绍了HttpWebRequest超时处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题.我正在使用HTTP POST将文件上传到服务器.事情是我需要专门处理连接超时,并在发生超时后添加一些等待算法以重现服务器.

I have a really simple question. I am uploading files to a server using HTTP POST. The thing is I need to specially handle connection timeouts and add a bit of a waiting algorithm after a timeout has occurred to relive the server.

我的代码非常简单:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SomeURI");
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.KeepAlive = true;
request.Accept = "*/*";
request.Timeout = 300000;
request.AllowWriteStreamBuffering = false;

try
{
      using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
      {
            WebHeaderCollection headers = response.Headers;    
            using (Stream Answer = response.GetResponseStream())
            {
                // Handle.
            }
      }
}
catch (WebException e)
{
    if (Timeout_exception)
    {
       //Handle timeout exception
    }
}

我忽略了文件读取代码,因为这与我们无关.现在,我需要确保一旦引发WebException,就对异常进行过滤以查看它是否确实是超时异常.我曾想将异常消息与之进行比较,但我不确定这是否是正确的方法,因为所讨论的应用程序是商业应用程序,而且恐怕消息会因不同语言而异.以及我要寻找什么消息.

I omitted the file reading code as it is not our concern. Now I need to make sure that once a WebException is thrown, I filter the exception to see if it is indeed a timeout exception. I thought of comparing against the exception message yet I am not sure if this is the right way since the application in question is a commercial app and I am afraid that the message varies between different languages. And what message should I be looking for.

有什么建议吗?

推荐答案

您可以查看

You can look at WebException.Status. The WebExceptionStatus enum has a Timeout flag:

try
{
   using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
   {
      WebHeaderCollection headers = response.Headers;    
      using (Stream answer = response.GetResponseStream())
      {
          // Do stuff
      }
   }
}
catch (WebException e)
{
   if (e.Status == WebExceptionStatus.Timeout)
   {
      // Handle timeout exception
   }
   else throw;
}

在这里使用C#6异常过滤器会很方便:

Using C# 6 exception filters can come in handy here:

try
{
    var request = WebRequest.Create("http://www.google.com");
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        WebHeaderCollection headers = response.Headers;
        using (Stream answer = response.GetResponseStream())
        {
            // Do stuff
        }
    }
}
catch (WebException e) when (e.Status == WebExceptionStatus.Timeout)
{
    // If we got here, it was a timeout exception.
}

这篇关于HttpWebRequest超时处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆