在Google App Engine上使用HttpsURLConnection来检索证书详细信息

时间:2016-10-05 15:52:01

标签: java google-app-engine ssl

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

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

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类的主方法中)。但是,在App Engine中运行时会引发以下异常:

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位于whitelist of allowed classes中,因此必须有一种方法可以在App Engine上使用此类(嗯,您可以假设)。您似乎无法使用URL.openConnection()。

有没有人知道建立HTTPS连接的方法(在App Engine上使用Java)并查看SSL证书的详细信息?

注意:我查看了Google的URLFetchService。似乎没有任何方法可以访问证书(仅限HTTP请求的内容)。

1 个答案:

答案 0 :(得分:1)

正如您(正确)观察到的那样,标准环境中的内置URLFetchService无法做到这一点。有关您可以使用URLFetchService和HTTPS执行的操作的详细信息,请参阅here。您可以使用第三方库来执行此操作,但request proxying也可以证明是障碍(尝试sockets API,也许?);您可以尝试使用flexible environment,具体取决于您的使用情况。