zoukankan      html  css  js  c++  java
  • 【转】C#中判断网址是否有效

    本文内容来源网络,如涉及版权,请联系作者删除。

    思路:C#语言判断网址是否正确,思路是向网址发起连接,根据状态判断网址是否有效。

    代码如下:

    //仅检测链接头,不会获取链接的结果。所以速度很快,超时的时间单位为毫秒
    public static string GetWebStatusCode(string url,int timeout) {
            HttpWebRequest req = null;
            try
            {
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                req.Method = "HEAD";  //这是关键        
                req.Timeout = timeout;
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                return Convert.ToInt32(res.StatusCode).ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally {
                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }
    
    }
         
    //需要注意的是如果你使用多线程。。C#默认同时只有4个网络线程,如需要破解此限制需要添加代码
    ServicePointManager.DefaultConnectionLimit = 100;
         
    //此方法返回一个状态码。。状态码为200是为正常,异常时会返回错误信息。比如超时
  • 相关阅读:
    POJ 1095 Trees Made to Order 最详细的解题报告
    Producter and Consumer
    How to use the function of bind
    How to use the functions of apply and call
    Configurate vim tool
    #4713. 方程
    #4709. 树
    #4718. 管理
    #4710. 并
    #4707. 点分治
  • 原文地址:https://www.cnblogs.com/gis9/p/9704768.html
Copyright © 2011-2022 走看看