如何检查URL是否有效?

时间:2013-03-31 09:03:46

标签: windows-phone-8

我希望能够检查指定的网址是否有效[最好是活动和良好形成],

例如

//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;
}

感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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;
    }