C# 访问被墙网站如何设置超时

最近使用 C# HttpWebRequest 写网络模块的时候,即使设置了 Timeout,也会在

Request = (HttpWebRequest)HttpWebRequest.Create(URL);

卡住,因为上面这段代码要判断服务器是否可访问,这里的超时是 20s,也就是说,如果这个网站被墙了,就会在这里卡 20s 左右,单独设置 HttpWebRequest.TimeOut 是无效的。

Karl Glennon问题 中说到

当我们检查的服务器停机时,无论我们尝试什么,我们都无法使超时小于21秒。为了解决这个问题,我们组合了 TcpClient 检查(查看域是否为活动的)和单独检查(查看URL是否为活动的)

解决办法是,先使用 TcpClient 判断 Url 是否活动,即

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值