JAVA - 简单的 GET 请求,使用 SSL 证书和 HTTPS [英] JAVA - Simple GET request, using SSL certificate and HTTPS

查看:81
本文介绍了JAVA - 简单的 GET 请求,使用 SSL 证书和 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file with the '.pfx' extension and a password to this certificate.

我需要做的是向网络服务发送一个简单的 GET 请求并读取响应正文.

What I need to do is to send a simple GET request to a webservice and read the response body.

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

I need to implement a method similar to this:

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

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

I also tried converting the certificate to a format "with no password" using 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

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

So the alternate implementaion of the my method could be:

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

我真的很感谢你的帮助,我花了半天的时间在谷歌上搜索它,但我还没有找到一个可以帮助我的例子,看来我在理解 SSL 和其他东西的一些基本假设时遇到了问题.

I would really appreciate your help, I spent half a day googling for it, but I haven't found an example that would help me, it seems I have problems with undestanding some basic assumptions around SSL and stuff.

推荐答案

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

I finally found a good solution (without creating custom SSL context):

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆