在Google应用引擎上使用HttpsURLConnection来检索证书详细信息



我正在开发一个Java应用程序-要在应用程序引擎上运行-它会定期检查我们的web应用程序使用的SSL证书,并在它们即将过期时给我们一个警告。

我希望使用以下代码,如果证书在不到2周内过期,则抛出异常(我通过删除一些错误检查简化了它)。

GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, 14);
Date twoWeeksInTheFuture = cal.getTime();
URL url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// Need the following line in order to establish a connection with the server
con.getResponseCode();
Certificate[] certs = con.getServerCertificates();
Certificate certificate = certs[0];
X509Certificate x509Certificate = (X509Certificate) certificate;
x509Certificate.checkValidity(twoWeeksInTheFuture);

该代码在App Engine之外工作得很好(例如在Java类的main方法中)。但是,当在应用引擎中运行时,会抛出以下异常:

java.lang.ClassCastException: com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection cannot be cast to javax.net.ssl.HttpsURLConnection
    at com.bronzelabs.httpschecker.servlets.cron.HttpsChecker.doGet(HttpsChecker.java:101)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)

HttpsURLConnection在允许类的白名单中,所以必须有一种方法在App Engine上使用这个类(好吧,你会假设)。就好像你不能使用URL.openConnection().

有没有人知道建立HTTPS连接的方法(在应用程序引擎上使用Java)和查看SSL证书的详细信息?

注意:我看过谷歌的URLFetchService。似乎没有任何方法可以访问证书(只有HTTP请求的内容)。

在标准环境中没有办法使用内置的URLFetchService来做到这一点,正如您(正确地)观察到的那样。有关可以使用URLFetchService和HTTPS做什么的详细信息,请参阅此处。你也许可以使用第三方库来做到这一点,但请求代理也可能被证明是一个障碍(尝试sockets API,也许?);您可以根据您的用例尝试使用灵活的环境。

最新更新