programing

문자열이 유효한 HTTP URL인지 확인하는 방법은 무엇입니까?

lastcode 2023. 5. 17. 23:14
반응형

문자열이 유효한 HTTP URL인지 확인하는 방법은 무엇입니까?

방법과 방법이 있지만 다시 돌아오는 것 같습니다.true파일 경로 등의 경우

문자열이 입력 유효성 검사 목적으로 유효한(반드시 활성화될 필요는 없음) HTTP URL인지 확인하려면 어떻게 해야 합니까?

HTTP URL의 유효성을 검사합니다(uriName테스트할 URI):

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

또는 HTTP 및 HTTPS URL을 모두 유효한 것으로 허용하려면(J0e3gan의 설명에 따라) 다음을 수행합니다.

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

이 방법은 http와 https 모두에서 잘 작동합니다.한 줄만 :)

if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))

MSDN: 올바른 형식의 UriString

시도:

bool IsValidURL(string URL)
{
    string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
    Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    return Rgx.IsMatch(URL);
}

다음과 같은 URL을 허용합니다.

  • http(s)//www.example.com
  • http(s)//stackoverflow.example.com
  • http(s)//www.example.com/page
  • http(s)//www.example.com/page?id=1&product=2
  • http(s)//www.example.com/page#start
  • http(s)//www.example.com:8080
  • http(s)//127.0.0.1
  • 127.0.0.1
  • www.example.com
  • example.com
    public static bool CheckURLValid(this string source)
    {
        Uri uriResult;
        return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
    }

용도:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

업데이트: (코드 한 줄)감사합니다. @GoClimb Colorado

public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;

용도:

string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
  //valid process
}

여기에 있는 모든 답변은 다른 체계(예:file://,ftp://)로 시작하지 않는 사용자가 읽을 수 있는 URL을 거부합니다.http://또는https://(예:www.google.com) 는 사용자 입력을 처리할 때 좋지 않습니다.

방법은 다음과 같습니다.

public static bool ValidHttpURL(string s, out Uri resultURI)
{
    if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
        s = "http://" + s;

    if (Uri.TryCreate(s, UriKind.Absolute, out resultURI))
        return (resultURI.Scheme == Uri.UriSchemeHttp || 
                resultURI.Scheme == Uri.UriSchemeHttps);

    return false;
}

용도:

string[] inputs = new[] {
                          "https://www.google.com",
                          "http://www.google.com",
                          "www.google.com",
                          "google.com",
                          "javascript:alert('Hack me!')"
                        };
foreach (string s in inputs)
{
    Uri uriResult;
    bool result = ValidHttpURL(s, out uriResult);
    Console.WriteLine(result + "\t" + uriResult?.AbsoluteUri);
}

출력:

True    https://www.google.com/
True    http://www.google.com/
True    http://www.google.com/
True    http://google.com/
False

끝나고Uri.TryCreate확인할 수 있습니다.Uri.SchemeHTTP인지 확인합니다.

정규식 사용에 대한 대안으로 이 코드는 다음을 사용합니다.Uri.TryCreateOP당 하지만 결과를 확인하여 Scheme이 http 또는 https 중 하나인지 확인합니다.

bool passed =
  Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult)
    && (uriResult.Scheme == Uri.UriSchemeHttp
      || uriResult.Scheme == Uri.UriSchemeHttps);

그러면 쿨이 반환됩니다.

Uri.IsWellFormedUriString(a.GetAttribute("href"), UriKind.Absolute)

문제:올바른 URL에는 https, http, www의 "접두사"가 모두 포함되어야 합니다.

  • URL에는 http:// 또는 https://가 포함되어야 합니다.
  • URL에는 하나의 www 인스턴스만 포함될 수 있습니다.
  • URL 호스트 이름 유형은 DNS여야 합니다.
  • URL 최대 길이는 100입니다.

솔루션:

public static bool IsValidUrl(string webSiteUrl)
{
   if (webSiteUrl.StartsWith("www."))
   {
       webSiteUrl = "http://" + webSiteUrl;
   }
        
   return Uri.TryCreate(webSiteUrl, UriKind.Absolute, out Uri uriResult)
            && (uriResult.Scheme == Uri.UriSchemeHttp
             || uriResult.Scheme == Uri.UriSchemeHttps) && uriResult.Host.Replace("www.", "").Split('.').Count() > 1 && uriResult.HostNameType == UriHostNameType.Dns && uriResult.Host.Length > uriResult.Host.LastIndexOf(".") + 1 && 100 >= webSiteUrl.Length;
}

유닛 테스트를 통해 검증됨

양성 단위 테스트:

    [TestCase("http://www.example.com/")]
    [TestCase("https://www.example.com")]
    [TestCase("http://example.com")]
    [TestCase("https://example.com")]
    [TestCase("www.example.com")]
    public void IsValidUrlTest(string url)
    {
        bool result = UriHelper.IsValidUrl(url);

        Assert.AreEqual(result, true);
    }

음의 단위 테스트:

    [TestCase("http.www.example.com")]
    [TestCase("http:www.example.com")]
    [TestCase("http:/www.example.com")]
    [TestCase("http://www.example.")]
    [TestCase("http://www.example..com")]
    [TestCase("https.www.example.com")]
    [TestCase("https:www.example.com")]
    [TestCase("https:/www.example.com")]
    [TestCase("http:/example.com")]
    [TestCase("https:/example.com")]
    public void IsInvalidUrlTest(string url)
    {
        bool result = UriHelper.IsValidUrl(url);

        Assert.AreEqual(result, false);
    }

참고: IsValidUrl 메서드는 example.com 과 같은 상대 URL 경로를 검증하지 않아야 합니다.

참조:

상대 URL 또는 절대 URL을 사용해야 합니까?

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

여기서url테스트해야 하는 문자열입니다.

URL 유효성 검사를 돕기 위해 이 기능을 만들었습니다. 원하는 대로 사용자 지정할 수 있습니다. 이 기능은 python3.10.6으로 작성되어 있습니다.

def url_validator(url: str) -> bool:
    """
    use this func to filter out the urls to follow only valid urls
    :param: url
    :type: str
    :return: True if the passed url is valid otherwise return false
    :rtype: bool
    """

    #the following regex is copied from Django source code 
    # to validate a url using regax
    
    regex = re.compile(
        r"^(?:http|ftp)s?://"  # http:// or https://
        r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|"  # domain...
        r"localhost|"  # localhost...
        r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"  # ...or ip
        r"(?::\d+)?"  # optional port
        r"(?:/?|[/?]\S+)$",
        re.IGNORECASE,
    )


    blocked_sites: list[str] = []

    for site in blocked_sites:
        if site in url or site == url:
            return False

    # if none of the above then ensure that the url is valid and then return True otherwise return False
    if re.match(regex, url):
        return True

    return False

언급URL : https://stackoverflow.com/questions/7578857/how-to-check-whether-a-string-is-a-valid-http-url

반응형