2

I want to validate url strings and add http://www if needed. The url may be "google.com" or "google.co.in" so it is hard to relay on the end of the string.

How can i do it?

Montoya
  • 2,479
  • 3
  • 27
  • 53

4 Answers4

2

You can try regular expression :

public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";

Pattern p = Pattern.compile(URL_REGEX);
Matcher m = p.matcher("example.com");//replace with string to compare
if(m.find()) {
    System.out.println("String contains URL");
}

Credit : https://stackoverflow.com/a/11007981/4211264

Community
  • 1
  • 1
Bhargav Thanki
  • 4,708
  • 2
  • 34
  • 43
1
if (!url.contains("http://www") {
    url = "http://www" + url;
}
Bartłomiej Semańczyk
  • 56,735
  • 45
  • 213
  • 327
Nirel
  • 1,827
  • 1
  • 13
  • 26
1

Well, in my opinion then best way to validate an URL is to actually try it. There are so many ways to screw up an URL and then there's the http:// or https:// thing.

Anyways here is an alternative if you want to actually test the URL to make sure it is truly valid and actually Online. Yes, I know it's much slower but at least you know for sure that it's good.

Here's the basic code:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class ValidateURL {


    public static void main(String[] args) {

        String urlString = "https://www.google.com";

        // Make sure "http://" or "https://" is located
        // at the beginning of the supplied URL.
        if (urlString.matches("((http)[s]?(://).*)")) {
            try {
                final URL url = new URL(urlString);
                HttpURLConnection huc = (HttpURLConnection) url.openConnection();
                int responseCode = huc.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("There was a problem connecting to:\n\n" + 
                            urlString + "\n\nResponse Code: [" + responseCode + "]");
                }
                System.out.println("The supplied URL is GOOD!"); 
            }  
            catch (UnknownHostException | MalformedURLException ex) { 
                System.out.println("Either the supplied URL is good or\n" + 
                        "there is No Network Connection!\n" + urlString);
            } 
            catch (IOException ex) { 
                System.out.println(ex.getMessage());
            }

        }
    }
}
DevilsHnd
  • 7,644
  • 2
  • 17
  • 21
0

If you just want to verify your String is valid URL, you can use Apache Validator class. Example code is there too.

Paresh P.
  • 6,393
  • 1
  • 13
  • 25