In Java how to simple way to check if URL is valid or invalid? Well there are multiple ways you could do that. In our tutorial, we will use org.apache.commons.validator.routines.UrlValidator
to validate any URLs.
Let’s get started:
- Create class CrunchifySimpleValidateURL.java
- Copy and paste below code.
package crunchify.com.java.tutorials; import org.apache.commons.validator.routines.UrlValidator; /** * @author Crunchify.com * Simple way to check if URL is valid or invalid? */ public class CrunchifySimpleValidateURL { public static void main(String[] args) { UrlValidator crunchifyURLValidator = new UrlValidator(); String url = "https://crunchify.com"; if (crunchifyURLValidator.isValid(url)) { crunchifyLog("Hey. URL " + url + " is valid"); } else { crunchifyLog("Hey. URL " + url + " is not valid"); } String invalidURL = "https://hey-crunchify.crunchify"; if (crunchifyURLValidator.isValid(invalidURL)) { crunchifyLog("Hey. URL " + invalidURL + " is valid"); } else { crunchifyLog("Hey. URL " + invalidURL + " is not valid"); } } private static void crunchifyLog(String s) { System.out.println(s); } }
We are using UrlValidator’s isValid() method. Here are more details.
isValid(String value)
method implementation.
Just run above program as a Java and you should see result like below.
Hey. URL https://crunchify.com is valid Hey. URL https://hey-crunchify.crunchify is not valid Process finished with exit code 0
Let me know if you face any issue running this program.
The post Simple way to check if URL is valid or invalid? How to Validate URLs in Java appeared first on Crunchify.
0 Commentaires