1

我希望能够检查指定的 URL 是否有效 [最好是 Active 和 Well Formed],

例如

//invalid
http://fdsafsd.com/
//valid
http://google.com/

可能吗?我正在使用stackoverflow中其他帖子上指定的代码,但它们似乎都不起作用。这是其中一个例子。

private bool checkWebsite(string url){
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try{
        //System.Net.WebRequest does not contain a definition for GetResponse();
        webResponse = webRequest.GetResponse();
    }
    catch
        return false;
    return true;
}

任何帮助表示赞赏。先感谢您。

4

2 回答 2

1

这应该适合你。虽然不是最优雅的代码。

static void Main(string[] args)
{
    var uriName = "http://www.google.com";
    Uri uriResult;

    bool isUriValid = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;

    if (isUriValid)
    {
        var webRequest = HttpWebRequest.Create(uriResult);
        // Only request the headers, not the whole content
        webRequest.Method = "HEAD";
        try
        {
            // Exception is thrown if 404
            var response = webRequest.GetResponse() as HttpWebResponse;
            // Check if status return is 200 OK, then active. You might want to check the HttpStatusCode for others
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine(((int)response.StatusCode).ToString());
            }
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message);
        }  
    }
    else
    {
        Console.WriteLine("Url is not valid");
    }

    Console.Read();
}
于 2013-04-01T11:42:27.610 回答
0

用 HttpClient 回答(您应该使用 System.Net.Http 添加;):

    private async Task<bool> IsURLAvailable(Uri url)
    {
        var httpClient = new HttpClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);
        HttpResponseMessage response = await httpClient.SendAsync(request);
        try
        {
            if (response.StatusCode == HttpStatusCode.OK)
                return true;
        }
        catch (WebException e)
        {
            Debug.WriteLine(e.Message);
        }
        return false;
    }
于 2013-08-02T20:15:46.553 回答