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?
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?
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");
}
if (!url.contains("http://www") {
url = "http://www" + url;
}
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());
}
}
}
}
If you just want to verify your String is valid URL, you can use Apache Validator class. Example code is there too.