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,819
  • 3
  • 37
  • 65

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,924
  • 2
  • 37
  • 43
1
if (!url.contains("http://www") {
    url = "http://www" + url;
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Nirel
  • 1,855
  • 1
  • 15
  • 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 - 退職した
  • 8,739
  • 2
  • 19
  • 22
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,677
  • 1
  • 14
  • 26