In this answer, we have shared how to check if an URL is valid or not using Java? We have used toURI()
method to validate URL, If the current URL is not properly formatted or, syntactically incorrect according to RFC 2396 this method throws a URISyntaxException.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.util.Scanner; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; public class ValidatingURL { public static boolean isUrlValid(String url) { try { URL obj = new URL(url); obj.toURI(); return true; } catch (MalformedURLException e) { return false; } catch (URISyntaxException e) { return false; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("Enter an URL"); String url = sc.next(); if(isUrlValid(url)) { URL obj = new URL(url); //Opening a connection HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //Sending the request conn.setRequestMethod("GET"); int response = conn.getResponseCode(); if (response == 200) { //Reading the response to a StringBuffer Scanner responseReader = new Scanner(conn.getInputStream()); StringBuffer buffer = new StringBuffer(); while (responseReader.hasNextLine()) { buffer.append(responseReader.nextLine()+"\n"); } responseReader.close(); //Printing the Response System.out.println(buffer.toString()); } }else { System.out.println("Enter valid URL"); } } } |
Program Output
1 2 3 | Enter an URL htps://www.freewebmentor.com/ Enter valid URL |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.