Java – Check if URL is HTTPS or HTTP protocol


I am currently using the following to read a file from android docs here and here. The user selects (in the settings screen) if their site uses HTTP or HTTPS protocol. If their website uses the HTTP protocol then it works for both HttpURLConnection and HttpsURLConnection, but if their site uses HTTPS protocol then it doesn't work for HttpURLConnection protocol and worst of all it doesn't give me an exception error. Below is the sample code that I am using.

So in essence, how can I check to see if the web url is HTTPS protocol so checking if the user selected the correct protocol?

InputStream inputStream;
HttpURLConnection urlConnection;
HttpsURLConnection urlHttpsConnection;
boolean httpYes, httpsYes; 
try {
if (httpSelection.equals("http://")) {
  URL url = new URL(weburi);
  urlConnection = (HttpURLConnection) url.openConnection();
  inputStream = new BufferedInputStream((urlConnection.getInputStream()));
httpYes = True;
if (httpSelection.equals("https://")) {
  URL url = new URL(weburi);
  urlHttpsConnection = (HttpsURLConnection) url.openConnection();
  inputStream = urlHttpsConnection.getInputStream();

catch (Exception e) {
//Toast Message displays and settings intent re-starts
finally {
    httpYes = False;
    httpsYes = False;


To elaborate some more. I need to see if it returns a valid response from a website? So if the user selected http instead of https how can I check to see if http is the incorrect prefix/protocol?

How can I check if the website uses HTTPS or HTTP protocol? If the user then only puts in say and I append https:// or http:// prefix to it, how do I know which one is the correct one to use?

Best Solution

You can Use android URLUtil to check whether url is HTTP or HTTPS:

public static boolean isHttpUrl (String url)
Returns True iff the url is an http: url.

public static boolean isHttpsUrl (String url) 
Returns True iff the url is an https: url.


public static boolean isValidUrl (String url)
Returns True iff the url is valid.