事实证明,你可以使用getServerCertificates()来检索证书链,它是在你启动HttpsURLConnection后获取的。HttpsURLConnection实现了TLS,这样你就可以确认证书是真实的,你与服务器的通信是保密的,数据的完整性得到了保留。
public void verifyCertificate(View view) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d("DEBUG", "Hello there");
try {
aFunctionWithCoolName("https://urlOfTheSiteYouWannaCheck.com");
Log.d("DEBUG", "Executed aFancyFunctionWithCoolName without any exceptions");
} catch (IOException e) {
e.printStackTrace();
Log.d("DEBUG", "IOException");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
Log.d("DEBUG", "NoSuchAlgorithmException");
} catch (CertificateEncodingException e) {
e.printStackTrace();
Log.d("DEBUG", "CertificateEncodingException");
} catch (CertificateParsingException e) {
e.printStackTrace();
Log.d("DEBUG", "CertificateParsingException");
} catch (Exception e) {
Log.wtf("DEBUG", "Too sad, I don't know what is happening :(");
}).start();
private static void aFunctionWithCoolName(String httpsURL) throws IOException, NoSuchAlgorithmException, CertificateEncodingException, CertificateParsingException {
final HttpsURLConnection con = (HttpsURLConnection) (new URL(httpsURL)).openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.connect();
// https://developer.android.com/reference/java/security/cert/X509Certificate
// https://developer.android.com/reference/java/security/cert/Certificate
// https://developer.android.com/reference/javax/net/ssl/HttpsURLConnection#getServerCertificates()
final Certificate[] certs = con.getServerCertificates();
final Certificate subjectCert = certs[0];
final Certificate rootCert = certs[certs.length-1];
if (subjectCert instanceof X509Certificate && rootCert instanceof X509Certificate) {
X509Certificate sc = (X509Certificate) subjectCert;
X509Certificate rc = (X509Certificate) rootCert;
printX509CertificateDetail(sc);
public static void printX509CertificateDetail(X509Certificate cert) {
Log.d("DEBUG", "===========================================");
Log.d("DEBUG - Subject DN", cert.getSubjectX500Principal().toString());
Log.d("DEBUG - Subject CN", getSubjectCommonName(cert));
Log.d("DEBUG - URL DN", url.getHost());