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

标签 java ssl https request certificate

我有一个扩展名为“.pfx”的文件和此证书的密码。

我需要做的是向网络服务发送一个简单的 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

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

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();
}

关于JAVA - 简单的 GET 请求,使用 SSL 证书和 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968708/

相关文章:

php - 在 cURL PHP 中为 https 启用 SSL 连接( header 空白)

java - 初始化默认 SSL 上下文失败

java - 如何在Java中比较sha1加密的密码?

java - Algid 解析错误,不是序列

java - 基于 SSL 的 XML RPC 服务,具有来自 Spring 应用程序的基本身份验证

ssl - 如何在网站之间共享自签名 TLS 证书

java - 线程。停止服务器

java - Windows Hello API

cookies - 使用 https 时是否应该对 cookie 内容进行加密?

.htaccess - 重写不适用于 ssl