Java에서 유효한 URL을 확인하려면 어떻게 해야 합니까?
Java에서 URL이 유효한지 확인하는 가장 좋은 방법은 무엇입니까?
전화를 걸려고 하면new URL(urlString)
그리고 잡는다MalformedURLException
, 그러나 그것은 무엇으로 시작하는 것들로 행복한 것처럼 보인다.http://
.
난 연관성에 대해선 관심 없어 단지 타당성일 뿐이야방법이 있을까요?휴지 상태 검증기의 주석?정규식을 써야 하나요?
편집: 허용되는 URL의 예는 다음과 같습니다.http://***
그리고.http://my favorite site!
.
Apache Commons UrlValidator 클래스 사용을 고려합니다.
UrlValidator urlValidator = new UrlValidator();
urlValidator.isValid("http://my favorite site!");
기본적으로 이 클래스의 동작을 제어하도록 설정할 수 있는 속성이 몇 가지 있습니다.http
,https
,그리고.ftp
인정됩니다.
이게 내가 노력한 방법이고 유용하다고 찾은 방법이야.
URL u = new URL(name); // this would check for the protocol
u.toURI(); // does the extra checking required for validation of URI
Tendayi Mauushe의 답변에 코멘트로 투고하고 싶지만, 공교롭게도 공간이 부족합니다.
Apache Commons UrlValidator 소스의 관련 부분을 다음에 나타냅니다.
/**
* This expression derived/taken from the BNF for URI (RFC2396).
*/
private static final String URL_PATTERN =
"/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
// 12 3 4 5 6 7 8 9
/**
* Schema/Protocol (ie. http:, ftp:, file:, etc).
*/
private static final int PARSE_URL_SCHEME = 2;
/**
* Includes hostname/ip and port number.
*/
private static final int PARSE_URL_AUTHORITY = 4;
private static final int PARSE_URL_PATH = 5;
private static final int PARSE_URL_QUERY = 7;
private static final int PARSE_URL_FRAGMENT = 9;
거기서, 독자적인 검증기를 간단하게 작성할 수 있습니다.
외부 라이브러리를 사용하지 않고 가장 선호하는 접근법:
try {
URI uri = new URI(name);
// perform checks for scheme, authority, host, etc., based on your requirements
if ("mailto".equals(uri.getScheme()) {/*Code*/}
if (uri.getHost() == null) {/*Code*/}
} catch (URISyntaxException e) {
}
가장 "foolproof"한 방법은 URL을 사용할 수 있는지 확인하는 것입니다.
public boolean isURL(String url) {
try {
(new java.net.URL(url)).openStream().close();
return true;
} catch (Exception ex) { }
return false;
}
어떤 구현도 마음에 들지 않았습니다(비싼 작업인 Regex나 한 가지 방법만 필요한 경우 오버킬인 라이브러리를 사용하기 때문에).그래서 java.net을 사용하게 되었습니다.URI 클래스에는 몇 가지 추가 검사가 있으며 프로토콜은 http, https, file, ftp, mailto, news, urn으로 제한됩니다.
예, 예외를 포착하는 작업은 비용이 많이 들 수 있지만 정규 표현만큼 나쁘지 않을 수 있습니다.
final static Set<String> protocols, protocolsWithHost;
static {
protocolsWithHost = new HashSet<String>(
Arrays.asList( new String[]{ "file", "ftp", "http", "https" } )
);
protocols = new HashSet<String>(
Arrays.asList( new String[]{ "mailto", "news", "urn" } )
);
protocols.addAll(protocolsWithHost);
}
public static boolean isURI(String str) {
int colon = str.indexOf(':');
if (colon < 3) return false;
String proto = str.substring(0, colon).toLowerCase();
if (!protocols.contains(proto)) return false;
try {
URI uri = new URI(str);
if (protocolsWithHost.contains(proto)) {
if (uri.getHost() == null) return false;
String path = uri.getPath();
if (path != null) {
for (int i=path.length()-1; i >= 0; i--) {
if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1)
return false;
}
}
}
return true;
} catch ( Exception ex ) {}
return false;
}
소스코드로 판단하면URI
,그
public URL(URL context, String spec, URLStreamHandler handler)
컨스트럭터는 다른 컨스트럭터보다 더 많은 검증을 수행합니다.한번 써보시겠지만 YMMV.
검증자 패키지:
요나탄 마탈론의 UrlUtil이라는 멋진 패키지가 있는 것 같습니다.API 인용:
isValidWebPageAddress(java.lang.String address, boolean validateSyntax,
boolean validateExistance)
Checks if the given address is a valid web page address.
Sun의 접근법 - 네트워크 주소 확인
Sun의 Java 사이트에서는 URL을 검증하기 위한 솔루션으로서 접속 시도를 제공합니다.
기타 regex 코드 스니펫:
Oracle 사이트 및 weberdev.com에서 regex 검증을 시도하고 있습니다.
언급URL : https://stackoverflow.com/questions/2230676/how-to-check-for-a-valid-url-in-java
'itsource' 카테고리의 다른 글
Vue.js를 사용하여 선택한 모든 확인란 목록을 가져옵니다. (0) | 2022.09.03 |
---|---|
uint8_t와 부호 없는 문자 (0) | 2022.09.03 |
JAX-RS 프로바이더의 의미 (0) | 2022.09.03 |
JSP를 사용하여 URL에서 파라미터를 취득하는 방법 (0) | 2022.09.03 |
변수 이름에 댓글을 달 수 있나요? (0) | 2022.09.03 |