-1

I am sending a request to a server to get some data, but before getting the data, I want to check whether the URL is on http or https.

How can I tell that, i.e. how can I check whether the URL is http or https?

I have a used a method in which I send a request to a server using http://. If a protocol exception occurs, then I again send a request to the server with https://. I can check it this way, but I don't want an exception to occur. Is there any way to check it again?

Follwoing is the code sample to send the request to server: Using OkHttp-

  try 
              { 

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                                    .url(url[0])
                                    .build();
                Response httpResponse = client.newCall(request).execute();
              }
              catch(IOException e)
              {
                Log.i("log","exception");


              }

Using HtppUrlConnection:

try 
                  { 

                HttpURLConnection.setFollowRedirects(true);
                con = (HttpURLConnection) new URL(url[0]).openConnection();
                con.setRequestMethod("GET");
                con.setConnectTimeout(10000);
                  }
                  catch(IOException e)
                  {
                    Log.i("log","exception");


                  }
Tarun Sharma
  • 601
  • 3
  • 13
  • 31
  • check this similar question ---------- http://stackoverflow.com/questions/1175096/how-to-find-out-if-you-are-using-https-without-serverhttps – prasad vsv Mar 11 '15 at 06:54
  • This is not similar. I don't want to write server side code.I want to get it checked in android. – Tarun Sharma Mar 11 '15 at 07:02
  • Tarun, can you paste the code you're trying to run that gives the exception for `http`? It's hard to help you without knowing how you get the URL in the first place, i.e. whether it's a string or something else. – Amos M. Carpenter Mar 11 '15 at 07:42

2 Answers2

0

Try debugging and inspecting whether or not the connection is an HttpURLConnection or an HttpsURLConnection at runtime. If this is the case, you can use introspection and cast the connection to the correct class type. E.g.:

if (con instanceOf HttpsURLConnection) { /* ... handle https ... */}

However I'm unsure about your question. You first construct a URL using an argument in new URL(url[0]). This implies you know the url in advance and hence know the protocol as well...

I'm assuming url[0] is a String. Can't you just do if(url[0].startsWith("https"))?

Alternatively, you could also first create a URL instance and then call getProtocol on the object.

RDM
  • 4,986
  • 4
  • 34
  • 43
0

Once you parse a String to URL, you can get the protocol:

URL url = new URL(my_url);
String protocol = url.getProtocol();

And the output will looks like http or https.

Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87