127

Visual C# 2005 で Yahoo! の銘柄記号を検索する簡単なプログラムを作成しています。Finance は履歴データをダウンロードし、指定されたティッカー シンボルの価格履歴をプロットします。

データを取得するために必要な正確な URL を知っており、ユーザーが既存のティッカー シンボル (または Yahoo! Finance のデータを含む少なくとも 1 つ) を入力すると、完全に正常に機能します。ただし、ユーザーがティッカー シンボルを作成すると、プログラムが存在しない Web ページからデータを取得しようとするため、実行時エラーが発生します。

私は WebClient クラスを使用しており、DownloadString 関数を使用しています。WebClient クラスの他のすべてのメンバー関数を調べましたが、URL のテストに使用できるものは見つかりませんでした。

これどうやってするの?

4

13 に答える 13

151

このソリューションの別の実装を次に示します。

using System.Net;

///
/// Checks the file exists or not.
///
/// The URL of the remote file.
/// True : If the file exits, False if file not exists
private bool RemoteFileExists(string url)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TRUE if the Status code == 200
        response.Close();
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        //Any exception will returns false.
        return false;
    }
}

から: http://www.dotnetthoughts.net/2009/10/14/how-to-check-remote-file-exists-using-c/

于 2010-09-28T00:20:16.417 に答える
119

「GET」ではなく「HEAD」リクエストを発行できますか? したがって、コンテンツをダウンロードするコストなしで URL をテストするには、次のようにします。

// using MyClient from linked post
using(var client = new MyClient()) {
    client.HeadOnly = true;
    // fine, no content downloaded
    string s1 = client.DownloadString("http://google.com");
    // throws 404
    string s2 = client.DownloadString("http://google.com/silly");
}

エラーをチェックするためにtry/catchの周りにします。DownloadStringエラーはありませんか?それが存在します...


C# 2.0 (VS2005) の場合:

private bool headOnly;
public bool HeadOnly {
    get {return headOnly;}
    set {headOnly = value;}
}

using(WebClient client = new MyClient())
{
    // code as before
}
于 2009-05-29T06:38:50.750 に答える
38

これらのソリューションは非常に優れていますが、200 OK 以外のステータス コードがある可能性があることを忘れています。これは、ステータス監視などのために本番環境で使用したソリューションです。

ターゲット ページに URL リダイレクトまたはその他の条件がある場合、このメソッドを使用すると true が返されます。また、GetResponse() は例外をスローするため、StatusCode を取得できません。例外をトラップし、ProtocolError を確認する必要があります。

400 または 500 のステータス コードは false を返します。他のすべては true を返します。このコードは、特定のステータス コードのニーズに合わせて簡単に変更できます。

/// <summary>
/// This method will check a url to see that it does not return server or protocol errors
/// </summary>
/// <param name="url">The path to check</param>
/// <returns></returns>
public bool UrlIsValid(string url)
{
    try
    {
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
        request.Method = "HEAD"; //Get only the header information -- no need to download any content

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            int statusCode = (int)response.StatusCode;
            if (statusCode >= 100 && statusCode < 400) //Good requests
            {
                return true;
            }
            else if (statusCode >= 500 && statusCode <= 510) //Server Errors
            {
                //log.Warn(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
                Debug.WriteLine(String.Format("The remote server has thrown an internal error. Url is not valid: {0}", url));
                return false;
            }
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
        {
            return false;
        }
        else
        {
            log.Warn(String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url), ex);
        }
    }
    catch (Exception ex)
    {
        log.Error(String.Format("Could not test url {0}.", url), ex);
    }
    return false;
}
于 2011-08-24T17:54:47.477 に答える
9

あなたの質問を正しく理解できれば、次のような簡単な方法を使用して、URL テストの結果を得ることができます。

WebRequest webRequest = WebRequest.Create(url);  
WebResponse webResponse;
try 
{
  webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
  return 0;
} 
return 1;

上記のコードをメソッドでラップし、それを使用して検証を実行できます。これがあなたが求めていた質問に答えることを願っています。

于 2009-05-29T07:07:07.837 に答える
6

これを試してください(System.Netを使用していることを確認してください):

public bool checkWebsite(string URL) {
   try {
      WebClient wc = new WebClient();
      string HTMLSource = wc.DownloadString(URL);
      return true;
   }
   catch (Exception) {
      return false;
   }
}

checkWebsite() 関数が呼び出されると、渡された URL のソース コードを取得しようとします。ソースコードを取得すると、true を返します。そうでない場合は false を返します。

コード例:

//The checkWebsite command will return true:
bool websiteExists = this.checkWebsite("https://www.google.com");

//The checkWebsite command will return false:
bool websiteExists = this.checkWebsite("https://www.thisisnotarealwebsite.com/fakepage.html");
于 2016-10-01T22:07:27.697 に答える
4

この解決策は従うのが簡単なようです:

public static bool isValidURL(string url) {
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch //If exception thrown then couldn't get response from address
    {
        return false ;
    }
    return true ;
}
于 2011-05-08T09:23:36.687 に答える
4

私は常に、例外の処理がはるかに遅いことに気づきました。

おそらく、集中力の少ない方法で、より良い、より速い結果が得られるでしょうか?

public bool IsValidUri(Uri uri)
{

    using (HttpClient Client = new HttpClient())
    {

    HttpResponseMessage result = Client.GetAsync(uri).Result;
    HttpStatusCode StatusCode = result.StatusCode;

    switch (StatusCode)
    {

        case HttpStatusCode.Accepted:
            return true;
        case HttpStatusCode.OK:
            return true;
         default:
            return false;
        }
    }
}

次に、次を使用します。

IsValidUri(new Uri("http://www.google.com/censorship_algorithm"));
于 2018-03-12T07:09:16.897 に答える
3

ここに別のオプションがあります

public static bool UrlIsValid(string url)
{
    bool br = false;
    try {
        IPHostEntry ipHost = Dns.Resolve(url);
        br = true;
    }
    catch (SocketException se) {
        br = false;
    }
    return br;
}
于 2012-05-01T04:43:23.277 に答える
1

Web サーバーは、リクエストの結果を示す HTTP ステータス コードで応答します。たとえば、200 (場合によっては 202) は成功、404 - 見つかりません (こちらを参照) を意味します。URL のサーバー アドレス部分が正しく、ソケット タイムアウトが発生していないと仮定すると、例外は、HTTP ステータス コードが 200 以外であったことを示している可能性が高いです。 HTTP ステータス コード。

IIRC - 問題の呼び出しが WebException または子孫をスローします。クラス名を調べてどのクラスかを確認し、呼び出しを try ブロックでラップして条件をトラップします。

于 2009-05-29T06:45:12.173 に答える
1

URL が有効かどうかを判断する簡単な方法があります。

if (Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
{
   //...
}
于 2012-02-20T05:19:01.190 に答える
1

すでに与えられた例に続いて、このような使用法で応答をラップすることもベストプラクティスだと思います

    public bool IsValidUrl(string url)
    {
         try
         {
             var request = WebRequest.Create(url);
             request.Timeout = 5000;
             request.Method = "HEAD";

             using (var response = (HttpWebResponse)request.GetResponse())
             {
                response.Close();
                return response.StatusCode == HttpStatusCode.OK;
            }
        }
        catch (Exception exception)
        { 
            return false;
        }
   }
于 2016-09-16T10:18:06.207 に答える