Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check protocol present in url or not?

Tags:

java

protocols

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

like image 694
udhaya Avatar asked Feb 20 '12 14:02

udhaya


3 Answers

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.

like image 62
hmjd Avatar answered Nov 15 '22 01:11

hmjd


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.

like image 45
Juvanis Avatar answered Nov 15 '22 00:11

Juvanis


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://");
}
like image 45
Shlomi Avatar answered Nov 14 '22 23:11

Shlomi