2017-07-10 3 views
0

URLが存在するか、または有効かどうかを確認するために、次の方法を使用しています。URLが有効かどうかを確認する-404 /見つからない

class MyClient : WebClient 
{ 
    public bool HeadOnly { get; set; } 

    protected override WebRequest GetWebRequest(Uri address) 
    { 
     WebRequest req = base.GetWebRequest(address); 

     if (HeadOnly && req.Method == "GET") 
     { 
      req.Method = "HEAD"; 
     } 
     return req; 
    } 
} 

private static Boolean CheckURL(string url) 
{ 
    using (MyClient myclient = new MyClient()) 
    { 
     try 
     { 
      myclient.HeadOnly = true; 
      // fine, no content downloaded 
      string s1 = myclient.DownloadString(url); 
      return true; 
     } 
     catch (Exception error) 
     { 
      return false; 
     } 
    } 
} 

私のアプローチは正しいですか?チェックされたURLのステータスを表示する方法:404、成功など?

助けてください。

+3

あなたはWebExceptionによって公開されたステータスコードを見てする必要があります:[Web応答ステータスコード](https://stackoverflow.com/questions/15289440/web-response-status-code)の可能性のある重複 –

+0

信じられないユーザエージェントヘッダーも含めるべきでしょう。 @AlexK。 –

+0

あなたはそれを答えとして追加してもいいですか。 – max

答えて

0

あなたの質問は答えです。

public static void isURLExist(string url) 
    { 
     try 
     { 
      WebRequest req = WebRequest.Create(url); 

      WebResponse res = req.GetResponse(); 

      Console.WriteLine("Url Exists"); 
     } 
     catch (WebException ex) 
     { 
      Console.WriteLine(ex.Message); 
      if (ex.Message.Contains("remote name could not be resolved")) 
      { 
       Console.WriteLine("Url is Invalid"); 
      } 
     } 
    } 
+0

特定のエラーメッセージが必要です... – max

+0

特定のメッセージそれはあなたの要件に依存します。 –

関連する問題