1. 程式人生 > >Spring boot 配置https 實現java通過https介面訪問

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