管理

网络操作类 - C#小函数类推荐

Posted on 2025-02-02 13:03  lzhdim  阅读(10485)  评论(0)    收藏  举报

       此文记录的是网络操作类。

/***

    网络操作类

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    Date:   2024-01-15 15:18:00

    使用方法:
        WebUtil.GetWebStatusCode("https://lzhdim.cnblogs.com/default.html",3000):

***/

namespace Lzhdim.LPF.Utility
{
    using System;
    using System.Net;

    /// <summary>
    /// 网络操作类
    /// </summary>
    public static class WebUtil
    {
        /// <summary>
        /// 获取网址,用于判断网址是否正确存在
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="timeout">超时时间</param>
        /// <returns>200 正确存在;其它不存在</returns>
        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;
                }
            }
        }
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved