1

I need a function which returns true if the certificate of a secure website is signed by a CA. In Android, if you try to connect to a self-signed certificate, it throws an SSLException, in this case I just catch it and return false. You can check the code:

public static boolean isValidCertificate(URL url) throws IOException {
    HttpsURLConnection con;
    try {
        con = (HttpsURLConnection) url.openConnection();
        con.connect();
        con.disconnect();
        return true;
    } catch (SSLException e) {
        return false;
    } 
}

My problem is that I want the function to throw an Exception if the site is not avaliable. But I just found out that Android throws the same SSLException in this case, with the same message: "No trusted server certificate".

Is there any way of knowing whether the server is online regardless of whether the certificate is valid or not?

Thanks!

SantiM
  • 192
  • 8
  • [Possible duplicate](http://stackoverflow.com/questions/1219208/is-it-possible-to-get-java-to-ignore-the-trust-store-and-just-accept-whatever) – npe Jun 21 '12 at 17:04
  • npe, I'm sorry but I am not asking how to avoid the CA check. Indeed, I already know how to do that. – SantiM Jun 21 '12 at 19:36
  • 1
    Then perhaps post full stack trace of the exception you're getting. And the code you use to trust all certificates. – npe Jun 21 '12 at 19:48
  • My code is all right, but I did a mistake, thank you because I've been thinking about your last post and I found the solution. I'll post it. – SantiM Jun 21 '12 at 20:46
  • ' if the site is not available ... Android throws the same SSLException in this case, with the same message: "No trusted server certificate".' I find this impossible to believe. It will throw a `ConnectException`, `NoRouteToHostException`, `UnknownHostException`, etc. You must be doing something very strange. – user207421 Jun 21 '12 at 23:09
  • Well, that was what I thought but you can see the code. And I swear you that when I had an url = https://10.0.2.2/fakeurl It threw an SSLException. I didn't understand how on earth could throw that exception. – SantiM Jun 23 '12 at 13:03

3 Answers3

2

Test it with a fake URL such as "https://flimflam.asdfasdfasdfg.com" and see what happens in your case.

If should fire off an IOException if no connection was made based on the openConnection method. Most likely this is more of a timeout and you'll spend time waiting for the timeout period.

Kirk
  • 16,182
  • 20
  • 80
  • 112
  • I tried with a fake URL and debug the function, it throws the same exception. That annoys me... – SantiM Jun 21 '12 at 17:30
1

try using con.getResponseCode(); before con.disconnect(); to get exception that you want.

Umer Hayat
  • 1,993
  • 5
  • 31
  • 58
0

I found the solution. I just need to check if the URL is online before calling this function. I can use my httpsclient without CA signed check and get the response, then, I call this method.

SantiM
  • 192
  • 8