捕获HttpWebRequest超时

编程入门 行业动态 更新时间:2024-10-26 14:39:30
本文介绍了捕获HttpWebRequest超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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; }

这段代码运行得很好,但是有时请求没有得到响应.当请求没有得到响应时,程序将挂起,然后最终将给出超时错误,使程序崩溃.我现在想做的只是捕获超时错误,以便我可以处理它,但似乎什么也没发现.

This code runs just fine, but sometimes the request does not get a response back. When the request doesn't get a response back the program will hang and then finally it will give a timeout error that crashes the program. All I am trying to do right now is just catch the timeout error so I can handle it, but nothing seems to be catching it.

推荐答案

最有可能在GetRequestStream()中超时. 文档特别指出,如果在以下情况下可能会抛出WebException:请求的过期时间已过期.

It is most likely timing out in GetRequestStream(). The documentation specifically states that it may throw WebException if the time-out period for the request expired.

因此,在您的try/catch中包含该代码块,您应该可以捕获它.

So include that block of code inside your try/catch and you should be able to catch it.

更多推荐

捕获HttpWebRequest超时

本文发布于:2023-11-05 19:38:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561663.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HttpWebRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!