【问题标题】:Catching HttpWebRequest Timeout捕获 HttpWebRequest 超时
【发布时间】:2013-01-31 20:09:40
【问题描述】:
public int loginEmail(string email, string password)
    {
        HttpWebRequest request = null;
        string responseStr = null;
        string Email = email;
        string Pass = password;

        UTF8Encoding encoding = new UTF8Encoding();
        string postData = "PostData";
        byte[] data = encoding.GetBytes(postData);

        request = (HttpWebRequest)WebRequest.Create("url");
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = false;
        request.KeepAlive = false;
        request.Proxy = null;
        request.ServicePoint.ConnectionLimit = 1000;
        request.ContentLength = data.Length;
        request.Timeout = 5000;
        request.ServicePoint.ConnectionLeaseTimeout = 5000;
        request.ServicePoint.MaxIdleTime = 5000;

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                responseStr = response.Headers["Set-Cookie"];
            }
        }
        catch
        {
            return 1;
        }

        string[] cooktemp;
        string[] seperatortemp = new string[] { ";" };
        cooktemp = responseStr.Split(seperatortemp, StringSplitOptions.None);

        LoginHeaders[0] = cooktemp[0] + ";";

        return 0;
    }

这段代码运行得很好,但有时请求没有得到响应。当请求没有得到响应时,程序将挂起,最后它会给出一个超时错误,导致程序崩溃。我现在要做的只是捕捉超时错误,以便我可以处理它,但似乎什么都没有捕捉到它。

【问题讨论】:

    标签: c# httpwebrequest timeout webrequest httpwebresponse


    【解决方案1】:

    很可能在GetRequestStream() 中超时。 documentation 明确指出,如果请求的超时期限到期,它可能会抛出 WebException。

    因此,在您的 try/catch 中包含该代码块,您应该能够捕获它。

    【讨论】:

      【解决方案2】:

      这是一个旧线程,但我今天也遇到了一个问题。

      我没有意识到的是,如果您有一个网络服务,比如说,它试图写入一个被锁定的文件...然后将代码放在一个简单的try..catch是不足够的。

      您必须专门有一个处理WebExceptions 的catch。

      try
      {
          //  Run your web service code
      }
      catch (WebException ex)
      {
          //  Handle a WebException, such as trying to write to a "locked" file on the network
      }
      catch (Exception ex)
      {
          //  Handle a regular Exception
      }
      

      我一直认为WebException 是Exception 的一种类型,所以这些会被catch 处理程序捕获:

      catch (Exception ex)
      {
          //  Handle a regular Exception
      }
      

      没有。

      因此,为了避免您的代码抛出“Request timed out”消息,并且没有任何关于导致它们的建议,请记住添加这些第二个 catch 处理程序。

      顺便说一句,在我的web services tutorial 上,这是我推荐的代码,它查找异常,并在响应标头中返回它们:

      try
      {
          //  Put your code in here
      }
      catch (WebException ex)
      {
          //  Return any exception messages back to the Response header
          OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
          response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
          response.StatusDescription = ex.Message.Replace("\r\n", "");
          return null;
      }
      catch (Exception ex)
      {
          //  Return any exception messages back to the Response header
          OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
          response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
          response.StatusDescription = ex.Message.Replace("\r\n", "");
          return null;
      }
      

      【讨论】:

        【解决方案3】:

        try { ... }            
        catch (System.Net.WebException sne)
                {
                    MessageBox.Show(req.Timeout.ToString());
                }
        

        无论如何,我认为超时将始终为“5000”。 如果你告诉它“超时为 5 秒”,它总是会尝试 5 秒然后放弃。

        【讨论】:

          猜你喜欢
          • 2011-03-21
          • 1970-01-01
          • 1970-01-01
          • 2015-01-28
          • 1970-01-01
          • 2012-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多