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

时间:2012-06-10 12:30:10

标签: java ssl https request certificate

我有一个带有'.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){
    ...
}

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

2 个答案:

答案 0 :(得分:9)

我终于找到了一个很好的解决方案(没有创建自定义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();
}

答案 1 :(得分:1)

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

HTTPClient-1.4.2: Explanation needed for Custom SSL Context Example

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

相关问题