Dino
Dino

Reputation: 561

get protocol from URL if not typed in

I am trying to find a way to get the protocol from a URL that the user types in. I have an EditText set as uri in an android layout file. The user types in his web address as www.thiersite.com or theirsite.com.

Now how can I get the correct protocol from what they have typed in? It seems everywhere I look that you need to have either https:// or http:// as the protocol in the http request. I get a malformed exception when I don't have a protocol for their web address.

Is there a way to check the URL without having the need to have the protocol when they typed their address? So in essence, do I need to ask the User to type in the protocol as part of the URL? I would prefer to do it programmatically.

Upvotes: 0

Views: 1069

Answers (1)

An SO User
An SO User

Reputation: 24998

/**
* Protocol value could be http:// or https://
*/
boolean usesProtocol(String url,String protocol){
    boolean uses = false;
    try{
        URL u = new URL( protocol.concat(url) );
        URLConnection con = u.openConnection();
        con.connect();
        // the following line will be hit only if the 
        // supplied protocol is supported
        uses = true;
    }catch(MalformedURLException e){
        // new URL() failed
        // user has made a typing error
    }catch(IOException e){
        // openConnection() failed
        // the supplied protocol is not supported
    }finally{
        return uses;
    }
}  

I believe that the code is self-explaining. The above code uses no external dependencies. If you do not mind using JSoup, there is another answer on SO that deals with the same: Java how to find out if a URL is http or https?

My Source: http://docs.oracle.com/javase/tutorial/networking/urls/connecting.html

Upvotes: 1

Related Questions