Reputation: 3648
I am writing a program where a user can input a URL but I need to check if it,s a real URL and not just some random string like abcdefg.gggg
. I am thinking about pinging the URL. What is the fastest way of doing that in java?
I am thinking something like this but would be happy if you have a faster alternative:
HttpURLConnection connection = null;
try {
URL u = new URL(urlstring);
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
if (code == 200) {
ok = true;
}
} catch (Exception error) {
// error
}
Upvotes: 0
Views: 2066
Reputation: 4038
Any provided URL can be validated in multiple ways. The key points to be kept in mind are
a. Url Syntax validation
public boolean isValidURL(String url) throws MalformedURLException {
UrlValidator urlValidator = new UrlValidator();
return validator.isValid(url);
}
Public boolean isValidURL(String url) throws MalformedURLException, URISyntaxException {
try {
new URL(url).toURI();
return true;
} catch (MalformedURLException e | URISyntaxException e) {
return false;
}
}
private static final String URL_REGEX =
"^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))" +
"(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)" +
"([).!';/?:,][[:blank:]])?$";
private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX);
public static boolean urlValidator(String url)
{
if (url == null) {
return false;
}
Matcher matcher = URL_PATTERN.matcher(url);
return matcher.matches();
}
b. Connectivity validation
public static String getStatus(String url) throws IOException {
String result = "";
try {
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(3000);
con.connect();
int code = con.getResponseCode();
if (code == 200) {
result = "On";
}
} catch (Exception e) {
result = "Off";
}
return result;
}
URL url = new URL(url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
InetAddress ipAddress = InetAddress.getByName(new URL(url).getHost());
Upvotes: 3
Reputation: 3062
Check url is valid or not by Patterns built-in class
boolean isUrlValid = Patterns.WEB_URL.matcher(urlstring).matches();
if (!isUrlValid) {
Toast.makeText(this, "Invalid Url", Toast.LENGTH_SHORT).show();
return;
}
Upvotes: 0