Spring boot 配置https 实现java通过https接口访问

Posted 别人眼中的过客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring boot 配置https 实现java通过https接口访问相关的知识,希望对你有一定的参考价值。

      近来公司需要搭建一个https的服务器来调试接口(服务器用的spring boot框架),刚开始接触就是一顿百度,最后发现互联网认可的https安全链接的证书需要去CA认证机构申请,由于是调试阶段就采用了java的keytool工具来生成密钥文件,下面是生成密钥文件的指令和步骤(前提是需要配置好java 的环境变量)。

  1、首先打开cmd命令,操作如下:

keytool -genkey -alias tomcat  -storetype PKCS12 -keyalg RSA -keysize 2048  -keystore keystore.p12 -validity 3650
1.-storetype 指定密钥仓库类型 
2.-keyalg 生证书的算法名称,RSA是一种非对称加密算法 
3.-keysize 证书大小 
4.-keystore 生成的证书文件的存储路径 
5.-validity 证书的有效期
根据提示完成操作,保存在操作时数据内容,最后keystore.p12为生成的密钥文件

   2、打开spring boot 项目工程,将keykeystore.p12文件放到项目的resources根目录中,同时在application.properties中添加如下代码:

#你生成的证书名字
server.ssl.key-store=classpath:keystore.p12
# 密钥库密码
server.ssl.key-store-password=第一步生成密钥文件时输入的密钥
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat

此时工程的https访问路径已经配置好了启动项目,打开浏览器就可以访问页面,不过会提示不安全链接,主要还是因为证书是不认的。

  3、通过java访问https接口代码如下:

import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 通过https访问服务器忽略证书没被认可也继续访问
 */
public class HttpsConnect extends BaseConnect {
    private static String TAG = "HttpConnect";

    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
   protected static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    protected static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] kb = new byte[1024];
        int len;
        while ((len = bais.read(kb)) != -1) {
            os.write(kb, 0, len);
        }
        os.flush();
        os.close();
        bais.close();
    }


    private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
        SSLContext ctx = null;
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();

        URL url = new URL(uri);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        httpsConn.setRequestMethod(method);
        if("post".equals(method.toLowerCase())) {
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
        }
        return httpsConn;
    }

    public static byte[] doGet(String uri) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
        return getBytesFromStream(httpsConn.getInputStream());
    }

    public static byte[] doPost(String uri, String data) throws IOException {
        HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
        setBytesToStream(httpsConn.getOutputStream(), data.getBytes("UTF-8"));
        return getBytesFromStream(httpsConn.getInputStream());
    }

}

 



以上是关于Spring boot 配置https 实现java通过https接口访问的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot如何配置SSL实现https协议

Spring Boot 中配置定时任务,实现多线程操作

Spring Boot SSL [https]配置例子

如何配置 IntelliJ HQL 控制台以使用 Spring Boot

Spring Boot 自动配置之@Conditional的使用

Spring Boot2.X 配置文件自动解密读取