0

i am checking if a string starts with "http://" or "https://". I want to add "http://" at the beginning with they aren't. However,

String str = "www.stackoverflow.com"
str = "http://" + str;

would result in

str = "http//stackoverflow.com"

The ":" in the middle is missing. What should I do?

Derekyy
  • 1,018
  • 4
  • 18
  • 31

3 Answers3

2

I used "android.webkit.URLUtil" class for checking Url. But it has its own limitation.

I detected that it allow spaces in urls.

// if url contains http://

 if(url.contains("http://")){
    // Validate URL
    if (!URLUtil.isValidUrl(url)) {

        Toast.makeText(getActivity(),"Invalid URL specified", Toast.LENGTH_SHORT).show();

        return;

         }else{ 

         // Your URL is Ready   

        }                       
         }else{// if url does not contains http://

        url = "http://" + url;  //add it to yur url 

         // Validate URL
        if (!URLUtil.isValidUrl(url)) { 
         Toast.makeText(getActivity(),"Invalid URL specified", Toast.LENGTH_SHORT).show();
             return;
            }else{ 
                    // Your link is ready   

                    }               
        }

URLUtil at Android developer

Stack Over flow Answer how to validate a URL / website name in EditText in Android?

Community
  • 1
  • 1
Tarun Sharma
  • 824
  • 1
  • 11
  • 24
2
if (URLUtil.isNetworkUrl(requestUrl)) {
           // it means url start with http or https
        }else{
      // do relevant action
     }
-1
String str = "www.stackoverflow.com"
str = "http://" + str;

The above one is resulting as expected only i.e., "http://www.stackoverflow.com" Can you post your exact code what are you doing there.

Supriya
  • 1,078
  • 1
  • 8
  • 16