---
title: "JAVA访问HTTPS/SSL接口"
author: "xilingyan"
date: "2014-06-04T13:51:00Z"
tags: []
categories: ["编程语言"]
slug: "java-https-ssl"
draft: false
lastmod: "2015-03-18T13:38:58Z"
id: 2075835
url: "https://xilingyan.iteye.com/blog/2075835"
---

解决思路：

1\. 调用接口前加载导入服务器证书的truststore（启动命令引入或代码里加载），这样只信任这个服务器证书（证书更新后，也不会信任，不推荐）

2\. 调用接口前加载导入服务器证书根证书的truststore，这样就会信任这个根证书签发的服务器证书，服务器证书更新也会信任（推荐）

3\. 调用接口前忽略证书信任，也就是相当于信任所有证书（不推荐）

4\. 调用接口前，获取到服务器证书，然后信任该证书（相当于第3条，但可以在过程中对证书的信息进行自定义验证）

 

1.2. 思路可使用以下方式：

1\. 代码方式：

            

```
System.setProperty("javax.net.ssl.keyStore", "d:/client.jks"); 
            System.setProperty("javax.net.ssl.keyStorePassword", "123456"); 
            System.setProperty("javax.net.ssl.keyStoreType", "JKS"); 
            System.setProperty("javax.net.ssl.trustStore", "d:/trust.jks");  // 将服务器证书或服务器证书的根证书添加至trust.jks
            System.setProperty("javax.net.ssl.trustStorePassword", "123123"); 
            System.setProperty("javax.net.ssl.trustStoreType", "JKS");
```

 

       2. JAVA运行命令中配置：

java -Djavax.net.ssl.keyStore=clientKeys    -Djavax.net.ssl.keyStorePassword=password    -Djavax.net.ssl.trustStore=clientTrust  -Djavax.net.ssl.trustStorePassword=password 

 

3 思路解决方法：

1\. Axis1.x使用方式

1.1 创建类MySocketFactory.java

```
import org.apache.axis.components.net.JSSESocketFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Hashtable;

public class MySocketFactory extends JSSESocketFactory {
    public MySocketFactory(Hashtable attributes) {
        super(attributes);
    }

    protected void initFactory() throws IOException {
        TrustManager[] myTrustManager = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };

        try {
            sc.init(null, myTrustManager, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        sslFactory = sc.getSocketFactory();
    }
}
```

 1.2 调用接口之前进行以下axis设置

```
AxisProperties.setProperty("axis.socketSecureFactory", "MySocketFactory"); //参数为类路径
```

 2. http方式

```
import javax.net.ssl.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class Test {

	public static void main(String[] args) {
		try {
			URL myURL = new URL("");
			TrustManager[] tm = {new MyX509TrustManager()};
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());

			//从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			//创建HttpsURLConnection对象，并设置其SSLSocketFactory对象
			HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
			httpsConn.setSSLSocketFactory(ssf);

			// 调用接口

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

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

	}

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

	}

	public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
		return null;
	}

	public boolean isClientTrusted(X509Certificate[] arg0) {
// TODO Auto-generated method stub
		return true;
	}

	public boolean isServerTrusted(X509Certificate[] arg0) {
// TODO Auto-generated method stub
		return true;
	}
}
```