C#检查url是否可用

  C#检查url是否可用,可以使用HttpWebRequest发送head请求获取服务器响应头,如果200状态说明存在,非200那就是服务端做了验证(如3xx响应头做跳转,说明可能有身份验证操作,4xx就是不可用了)。

  C#检查url是否可用源代码如下,xxx.aspx

using System;
using System.Net;
public partial class xxx: System.Web.UI.Page
{
    public static string GetUrlState(string url)
    {
        string state = "";
        try
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "head";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            state = ((int)response.StatusCode).ToString();
        }
        catch (WebException we)
        {
            state = ((int)((HttpWebResponse)(we.Response)).StatusCode).ToString();
        }
        return state;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string state = GetUrlState("http://www.w3dev.cn/bbb.rar");
        Response.Write(state);//404
    }
}

 


原创文章,转载请注明出处:C#检查url是否可用

评论(0)Web开发网
阅读(51)喜欢(0)Asp.Net/C#