Java HTTPS配置案例

wen java案例 3

本文目录导读:

Java HTTPS配置案例

  1. Java客户端HTTPS配置
  2. Java服务端HTTPS配置
  3. 使用HttpClient库(Apache HttpClient)
  4. 生成自签名证书(用于测试)
  5. 最佳实践建议

我来为您提供一个完整的Java HTTPS配置案例,涵盖客户端和服务端两种场景。

Java客户端HTTPS配置

1 基础HTTPS请求示例

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.X509Certificate;
public class HttpsClientExample {
    public static void main(String[] args) {
        try {
            String httpsUrl = "https://api.example.com/data";
            String response = sendHttpsRequest(httpsUrl);
            System.out.println("Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String sendHttpsRequest(String httpsUrl) throws Exception {
        URL url = new URL(httpsUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        // 设置请求方法
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        // 设置请求头
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        // 读取响应
        BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }
}

2 配置自定义SSLContext

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class HttpsClientWithSSL {
    public static void main(String[] args) {
        try {
            // 方式1:信任所有证书(仅用于测试)
            HttpsURLConnection.setDefaultSSLSocketFactory(
                createTrustAllSSLContext().getSocketFactory());
            // 方式2:使用自定义信任库
            HttpsURLConnection.setDefaultSSLSocketFactory(
                createCustomSSLContext().getSocketFactory());
            String response = sendHttpsRequest("https://example.com");
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 创建信任所有证书的SSLContext(仅测试环境使用)
    private static SSLContext createTrustAllSSLContext() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[] {
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(X509Certificate[] certs, 
                    String authType) {}
                public void checkServerTrusted(X509Certificate[] certs, 
                    String authType) {}
            }
        };
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc;
    }
    // 创建使用自定义证书库的SSLContext
    private static SSLContext createCustomSSLContext() throws Exception {
        // 加载信任库
        KeyStore trustStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream("/path/to/truststore.jks")) {
            trustStore.load(fis, "truststore_password".toCharArray());
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        // 加载密钥库(如果需要客户端认证)
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream("/path/to/keystore.p12")) {
            keyStore.load(fis, "keystore_password".toCharArray());
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "key_password".toCharArray());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), 
            new java.security.SecureRandom());
        return sc;
    }
    private static String sendHttpsRequest(String httpsUrl) throws Exception {
        URL url = new URL(httpsUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }
}

Java服务端HTTPS配置

1 使用Spring Boot配置HTTPS

application.yml配置:

server:
  port: 8443
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: changeit
    key-store-type: PKCS12
    key-alias: tomcat
    protocol: TLS
    enabled-protocols: TLSv1.2,TLSv1.3
    ciphers: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
# HTTP重定向到HTTPS
server:
  http:
    port: 8080

2 编程式配置Tomcat HTTPS

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
@Configuration
public class HttpsConfig {
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        // 添加HTTP连接器(自动重定向到HTTPS)
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }
    private Connector createStandardConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
    // 或者使用编程方式配置HTTPS连接器
    private Connector createHttpsConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("https");
        connector.setPort(8443);
        connector.setSecure(true);
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        protocol.setSSLEnabled(true);
        protocol.setKeystoreFile(new File("/path/to/keystore.p12").getAbsolutePath());
        protocol.setKeystorePass("changeit");
        protocol.setKeystoreType("PKCS12");
        protocol.setKeyAlias("tomcat");
        protocol.setSslProtocol("TLS");
        return connector;
    }
}

3 使用Java原生ServerSocket

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
public class HttpsServerExample {
    public static void main(String[] args) {
        int port = 8443;
        try {
            // 创建SSLServerSocket
            SSLServerSocketFactory ssf = createSSLServerSocketFactory();
            SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(port);
            // 设置支持的密码套件
            serverSocket.setEnabledCipherSuites(new String[] {
                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
                "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
            });
            System.out.println("HTTPS Server started on port " + port);
            while (true) {
                SSLSocket socket = (SSLSocket) serverSocket.accept();
                new Thread(new HttpsHandler(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static SSLServerSocketFactory createSSLServerSocketFactory() 
            throws Exception {
        // 加载密钥库
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (FileInputStream fis = new FileInputStream("/path/to/keystore.p12")) {
            ks.load(fis, "changeit".toCharArray());
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "changeit".toCharArray());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
        return sc.getServerSocketFactory();
    }
    static class HttpsHandler implements Runnable {
        private SSLSocket socket;
        public HttpsHandler(SSLSocket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(socket.getOutputStream()));
                // 读取HTTP请求
                String requestLine = in.readLine();
                System.out.println("Request: " + requestLine);
                // 发送HTTP响应
                out.println("HTTP/1.1 200 OK");
                out.println("Content-Type: text/html");
                out.println();
                out.println("<html><body>");
                out.println("<h1>Hello, HTTPS!</h1>");
                out.println("</body></html>");
                out.flush();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

使用HttpClient库(Apache HttpClient)

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
public class ApacheHttpClientExample {
    public static void main(String[] args) {
        try {
            // 方式1:基础HTTPS请求
            String response = basicHttpsRequest("https://api.example.com/data");
            System.out.println("Response: " + response);
            // 方式2:使用自定义SSL配置
            String response2 = sslHttpsRequest("https://api.example.com/data");
            System.out.println("Response: " + response2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String basicHttpsRequest(String url) throws Exception {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : "";
            }
        }
    }
    public static String sslHttpsRequest(String url) throws Exception {
        // 加载自定义信任库
        KeyStore trustStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream("/path/to/truststore.jks")) {
            trustStore.load(fis, "truststore_password".toCharArray());
        }
        SSLContext sslContext = SSLContextBuilder.create()
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext,
            new String[] {"TLSv1.2", "TLSv1.3"},
            null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : "";
            }
        }
    }
}

生成自签名证书(用于测试)

# 生成自签名证书
keytool -genkey -alias tomcat -keyalg RSA -keystore keystore.p12 \
  -storepass changeit -keypass changeit -storetype PKCS12 \
  -dname "CN=localhost, OU=IT, O=Company, L=City, ST=State, C=CN" \
  -validity 3650
# 导出证书
keytool -export -alias tomcat -keystore keystore.p12 \
  -storepass changeit -storetype PKCS12 -rfc -file server.cer
# 导入到信任库
keytool -import -alias tomcat -file server.cer \
  -keystore truststore.jks -storepass changeit -noprompt

最佳实践建议

  1. 生产环境:使用受信任的CA颁发的证书
  2. 密码保护:敏感信息使用环境变量或加密存储
  3. 协议版本:启用TLS 1.2+,禁用SSLv3和TLS 1.0/1.1
  4. 密码套件:使用强加密算法,禁用弱加密
  5. 证书验证:生产环境不要跳过证书验证
  6. 连接池:复用SSL连接以提高性能

这些示例涵盖了Java中HTTPS配置的主要场景,您可以根据具体需求选择合适的方式。

上一篇Java HSTS案例

下一篇Java CSP案例

抱歉,评论功能暂时关闭!