gpt4 book ai didi

c# - HttpWebRequest超时处理

转载 作者:IT王子 更新时间:2023-10-29 04:24:02 25 4
gpt4 key购买 nike

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

我的代码很简单:

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,我就会过滤该异常以查看它是否确实是超时异常。我考虑过与异常消息进行比较,但我不确定这是否是正确的方法,因为有问题的应用程序是商业应用程序,而且我担心消息会因不同语言而异。我应该寻找什么消息。

有什么建议吗?

最佳答案

可以看看WebException.Status . WebExceptionStatus 枚举有一个 Timeout 标志:

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 异常过滤器在这里可以派上用场:

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.
}

关于c# - HttpWebRequest超时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27212241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com