简单来说就是用了Certificate和HttpsURLConnection这俩类实现的。
后者获得连接,前者通过连接拿到证书。
private Date startDate; // Validity Period Start Time
private Date stopDate; // Validity Period Stop Time
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// use for print log
private void getCertificateDate() {
getCertificateDateThread.start();
}
private Thread getCertificateDateThread = new Thread(new Runnable() {
@Override
public void run() {
HttpsURLConnection connection = null;
try {
URL url = new URL("要拿证书的ip");
connection = (HttpsURLConnection) url.openConnection();
Slog.w(TAG, "getCertificateDateThread start and url is " + url.toString());
connection.connect();
for (Certificate certificate : connection.getServerCertificates()) {
// The first is the server's own certificate, followed by other certificates on the certificate chain
X509Certificate x509Certificate = (X509Certificate) certificate;
startDate = x509Certificate.getNotBefore();
stopDate = x509Certificate.getNotAfter();
Slog.d(TAG, "getCertificateDate and startDate : " + simpleDateFormat.format(startDate) + " , stopDate : " + simpleDateFormat.format(stopDate));
break;
}
connection.disconnect();
Slog.w(TAG, "Connection disconnect and getCertificateDateThread stop.");
} catch (IOException e) {
e.printStackTrace();
}
}
});
补充:判断两个date的先后,可以用Date类本身的before/after方法