Reputation: 312
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!
Upvotes: 1
Views: 1249
Reputation: 312
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.
Upvotes: 0
Reputation: 2001
try using con.getResponseCode();
before con.disconnect();
to get exception that you want.
Upvotes: 1
Reputation: 16265
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.
Upvotes: 2