如何以编程方式添加自签名证书以从Java代码发出HTTPS请求? [英] How to programmatically add self signed certificate for making a HTTPS request from java code?

查看:179
本文介绍了如何以编程方式添加自签名证书以从Java代码发出HTTPS请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码片段是从 HTTP URL获得 JSon 响应:

  private static void getJson(String location){
try {
try {
createSSLSocket();
网址=新网址(
https://abc.com/key/one);
HttpURLConnection conn =(HttpURLConnection)url
.openConnection();
conn.setRequestMethod(GET);
conn.setRequestProperty(Accept,application / json); ($ conn.getResponseCode());
if
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
字符串输出;
System.out.println(从服务器输出... \\\
); ((output = br.readLine())!= null){
System.out.println(output);
while
}
conn.disconnect();

catch(MalformedURLException e){
e.printStackTrace();

} catch(IOException e){
e.printStackTrace();
$ b}
} catch(Exception ex){
ex.printStackTrace();
}

}

但它会抛出 SSLHandhaking 异常,因为我没有为代码添加自签名认证异常。我已经在 C#中完成了这项工作,但不是在java中完成的。我应该执行哪些步骤?需要您的建议:)



预先感谢您。 可以配置 HttpsURLConnection 套接字工厂接受没有任何验证的所有证书:

  private class TrustAll implements X509TrustManager 
{
public void checkClientTrusted(X509Certificate [] x509Certificates,String s)throws CertificateException
{
}

public void checkServerTrusted (X509Certificate [] x509Certificates,String s)throws CertificateException
{
}

public X509Certificate [] getAcceptedIssuers()
{
return new X509Certificate [0 ]。
}
}

SSLContext ctx = SSLContext.getInstance(TLS);
ctx.init(null,new TrustManager [] {new TrustAll()},null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

更新

你只需在应用程序的开始处调用一次该代码。所有使用 URL.openConnection()打开的HTTPS连接都将使用此套接字工厂。另一种解决方案可能是将此代码添加到 createSSLSocket()方法体中。


Following code snippet is to get JSon response from a HTTP URL:

private static void getJson(String location) {
    try {
        try {
            createSSLSocket();
            URL url = new URL(
                    "https://abc.com/key/one");
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

But it is throwing SSLHandshaking exception because i didn't added self signed certification exception to the code. I have done this in C# but not in java. What steps should i perform? Need your suggestion :)

Thanks in advance.

解决方案

You can configure the HttpsURLConnection socket factory to accept all certificate without any validation:

private class TrustAll implements X509TrustManager
{
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public X509Certificate[] getAcceptedIssuers()
    {
        return new X509Certificate[0];
    }
}

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { new TrustAll() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

UPDATE

You just have to call this code once at the start of the application. All HTTPS connections opened with URL.openConnection() will use this socket factory. Another solution could be adding this code in the createSSLSocket() method body.

这篇关于如何以编程方式添加自签名证书以从Java代码发出HTTPS请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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