[c#] C # URL이 있는지 / 유효한지 어떻게 확인할 수 있습니까?

저는 Yahoo!에서 주식 기호를 조회하는 Visual C # 2005에서 간단한 프로그램을 만들고 있습니다. Finance는 기록 데이터를 다운로드 한 다음 지정된 종목 기호에 대한 가격 기록을 플로팅합니다.

데이터를 수집하는 데 필요한 정확한 URL을 알고 있으며 사용자가 기존 시세 기호 (또는 Yahoo! Finance의 데이터가있는 하나 이상)를 입력하면 완벽하게 작동합니다. 그러나 프로그램이 존재하지 않는 웹 페이지에서 데이터를 가져 오려고 할 때 사용자가 시세 기호를 구성하면 런타임 오류가 발생합니다.

WebClient 클래스를 사용하고 있으며 DownloadString 함수를 사용하고 있습니다. WebClient 클래스의 다른 모든 멤버 함수를 살펴 보았지만 URL을 테스트하는 데 사용할 수있는 내용이 보이지 않았습니다.

어떻게 할 수 있습니까?



답변

“HEAD”를 발행 할 수 있습니다.“GET”대신 요청을 있습니까?

(편집)-lol! 이전에이 작업을 수행것 같습니다 !; rep-garnering의 비난을 피하기 위해 위키로 변경되었습니다. 따라서 콘텐츠 다운로드 비용없이 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
}


답변

다음은이 솔루션의 또 다른 구현입니다.

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/


답변

이러한 솔루션은 꽤 좋지만 200 OK 이외의 다른 상태 코드가있을 수 있다는 사실을 잊고 있습니다. 이것은 상태 모니터링 등을 위해 프로덕션 환경에서 사용한 솔루션입니다.

URL 리디렉션 또는 대상 페이지에 다른 조건이있는 경우이 메서드를 사용하면 반환이 true가됩니다. 또한 GetResponse ()는 예외를 throw하므로 이에 대한 StatusCode를 얻지 못합니다. 예외를 트랩하고 ProtocolError를 확인해야합니다.

400 또는 500 상태 코드는 false를 반환합니다. 다른 모든 것은 사실을 반환합니다. 이 코드는 특정 상태 코드에 대한 요구에 맞게 쉽게 수정할 수 있습니다.

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


답변

질문을 올바르게 이해했다면 다음과 같은 작은 방법을 사용하여 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;

위 코드를 메서드에 래핑하고이를 사용하여 유효성 검사를 수행 할 수 있습니다. 이 질문에 대한 답변이 되었기를 바랍니다.


답변

이것을 시도하십시오 (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를 반환합니다. 그렇지 않으면 거짓을 반환합니다.

코드 예 :

//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");


답변

다른 옵션이 있습니다.

public static bool UrlIsValid(string url)
{
    bool br = false;
    try {
        IPHostEntry ipHost = Dns.Resolve(url);
        br = true;
    }
    catch (SocketException se) {
        br = false;
    }
    return br;
}


답변

이 솔루션은 따라하기 쉽습니다.

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