HttpWebRequest超时处理

编程入门 行业动态 更新时间:2024-10-26 12:25:47
本文介绍了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.

有什么建议吗?

推荐答案

您可以查看 WebException.Status . WebExceptionStatus枚举具有Timeout标志:

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("www.google"); 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超时处理

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

发布评论

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

>www.elefans.com

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