c# - 如何在执行 Web 请求时指定仅连接超时?

标签 c# httpwebrequest dotnet-httpclient

我目前正在使用使用 HttpClient 类发出 HTTP 请求的代码。尽管您可以为请求指定超时,但该值适用于整个请求(包括解析主机名、建立连接、发送请求和接收响应)。

我需要一种方法让请求在无法解析名称或建立连接时快速失败,但有时我也需要接收大量数据,因此不能仅仅减少超时。

有没有办法使用内置 (BCL) 类或替代 HTTP 客户端堆栈来实现此目的?

我简要地查看了 RestSharp 和 ServiceStack,但它们似乎都没有为连接部分提供超时(但如果我错了请纠正我)。

最佳答案

如果连接花费太多时间,您可以使用 Timer 中止请求。时间到时添加事件。你可以使用这样的东西:

static WebRequest request;
private static void sendAndReceive()
{
    // The request with a big timeout for receiving large amout of data
    request = HttpWebRequest.Create("http://localhost:8081/index/");
    request.Timeout = 100000;

    // The connection timeout
    var ConnectionTimeoutTime = 100;
    Timer timer = new Timer(ConnectionTimeoutTime);
    timer.Elapsed += connectionTimeout;
    timer.Enabled = true;

    Console.WriteLine("Connecting...");
    try
    {
        using (var stream = request.GetRequestStream())
        {
            Console.WriteLine("Connection success !");
            timer.Enabled = false;

            /*
             *  Sending data ...
             */
            System.Threading.Thread.Sleep(1000000);
        }

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            /*
             *  Receiving datas...
             */
        }
    }
    catch (WebException e)
    {
        if(e.Status==WebExceptionStatus.RequestCanceled) 
            Console.WriteLine("Connection canceled (timeout)");
        else if(e.Status==WebExceptionStatus.ConnectFailure)
            Console.WriteLine("Can't connect to server");
        else if(e.Status==WebExceptionStatus.Timeout)
            Console.WriteLine("Timeout");
        else
            Console.WriteLine("Error");
    }
}

static void connectionTimeout(object sender, System.Timers.ElapsedEventArgs e)
{
    Console.WriteLine("Connection failed...");
    Timer timer = (Timer)sender;
    timer.Enabled = false;

    request.Abort();
}

这里的时间只是举例,您可以根据自己的需要进行调整。

关于c# - 如何在执行 Web 请求时指定仅连接超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26962615/

相关文章:

c# - 机器特定的 HttpWebResponse 超时

c# - 如何限制每秒对网络服务器的 HttpWebRequest 数量?

c# - 如何在 C# 8+ 中从 WebAPI 发送 IAsyncEnumerator 并通过 HttpClient 传输数据?

c# - HttpClient的多种实现

c# - DataGridView 替换值

c# - 如何在 Quartz.net 中随时开始工作?

c# - 使用 BindIPEndPointDelegate 指定源端口似乎不起作用

c# - 如何找到 SpeechSynthesizer 所选语音的音频格式

c# - 如何在 OpenTK 中翻转 QuickFont

c# - 使用 HttpClient,发送一个没有模式的授权 token