JAVA – 使用SSL证书和HTTPS的简单GET请求

我有一个带有’.pfx’扩展名的文件和这个证书的密码。

我需要做的是向web服务发送一个简单的GET请求并阅读响应正文。

我需要实现一个类似于此的方法:

String getHttpResponse(String url, String certificateFile, String passwordToCertificate){ ... } 

我还尝试使用openssl将证书转换为“无密码”格式:

 Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM: openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes 

所以我的方法的替代实现可能是:

 String getHttpResponse(String url, String certificateFile){ ... } 

我真的很感谢你的帮助,我花了半天的时间用谷歌搜索它,但是我还没有找到一个可以帮助我的例子,似乎我有一些关于SSL和东西的一些基本假设的问题。

我终于找到了一个很好的解决方案(不创建自定义SSL上下文):

 String getHttpResponseWithSSL(String url) throws Exception { //default truststore parameters System.setProperty("javax.net.ssl.trustStore", "/usr/lib/jvm/java-6-openjdk/jre/lib/securitycacerts"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); //my certificate and password System.setProperty("javax.net.ssl.keyStore", "mycert.pfx"); System.setProperty("javax.net.ssl.keyStorePassword", "mypass"); System.setProperty("javax.net.ssl.keyStoreType", "PKCS12"); HttpClient httpclient = new HttpClient(); GetMethod method = new GetMethod(); method.setPath(url); int statusCode = httpclient.executeMethod(method); System.out.println("Status: " + statusCode); method.releaseConnection(); return method.getResponseBodyAsString(); } 

这个问题应该有你的答案:

HTTPClient-1.4.2:自定义SSL上下文示例所需的说明

您需要使用httpclient来创建请求,然后使用密钥管理器。