how to check protocol is present in URL , if not present need to append it. is there any class to achieve this in java? eg: String URL = www.google.com
need to get http://www.google.com
Just use String.startsWith("http://")
to check this.
public String ensure_has_protocol(final String a_url)
{
if (!a_url.startsWith("http://"))
{
return "http://" + a_url;
}
return a_url;
}
EDIT:
An alternative would use a java.net.URL
instance, whose constructor would throw an java.net.MalformedURLException
if the URL did not contain a (legal) protocol (or was invalid for any other reason):
public URL make_url(final String a_url) throws MalformedURLException
{
try
{
return new URL(a_url);
}
catch (final MalformedURLException e)
{
}
return new URL("http://" + a_url);
}
You can use URL.toString()
to obtain string representation of the URL. This is an improvement on the startsWith()
approach as it guarantees that return URL is valid.
Let's say you have String url = www.google.com
. String class methods would be enough for the goal of checking protocol identifiers. For example, url.startsWith("https://")
would check whether a specific string is starting with the given protocol name.
However, are these controls enough for validation?
I think they aren't enough. First of all, you should define a list of valid protocol identifiers, e.g. a String array like {"http", "ftp", "https", ...
}. Then you can parse your input String with regex ("://")
and test your URL header whether it belongs to the list of valid protocol identifiers. And domain name validation methods are beyond this question, you can/should handle it with different techniques as well.
Just for completeness, I would do something like the following:
import com.google.common.base.Strings;
private static boolean isUrlHttps(String url){
if(Strings.isNullOrEmpty(url))
return false;
return url.toLowerCase().startsWith("https://");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With