0

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.

3
  • Do you ever expect something other than http or https? If no, just add one of those. Commented Feb 15, 2015 at 15:51
  • No it has to be either one or the other. Commented Feb 15, 2015 at 15:59
  • Check whether string starts with "http". If not, add http:// Commented Feb 15, 2015 at 16:03

1 Answer 1

1
/**
* 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

Sign up to request clarification or add additional context in comments.

5 Comments

Am I correct in assuming that Java can not get a http request without the protocol in front of the URL such as https:// or http://? So a malformed exception will occur if www.theirsite.com does not have https:// or http:// in front of it?
@Dino You are correct. You can read the docs here: docs.oracle.com/javase/7/docs/api/java/net/URL.html Also note that raising exceptions is an expensive process. Consider caching the URLs for further use.
I was wondering about that, I think I will not do this method and ask them to select https:// or http://
The implementation is completely yours :)
Yes very true, just trying to develop for the "lazy user".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.