httpclient-ssl+https校验+springboot ssl

HttpClientUtil


/**
 * HTTPClient工具类
 */
public class HttpClientUtil {
    private static final String EMPTY_STR = "";
    private static final String UTF_8 = "UTF-8";
    private static final int MAX_TIMEOUT = 100000;
    private static PoolingHttpClientConnectionManager cm;
    private static RequestConfig requestConfig;
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);
    private static CloseableHttpClient httpClient;
    private static final String keyStorePath = "d:/keystore/xxx.keystore";
    private static final String keyStorePwd = "xxxx";

    public static void main(String[] args) {
        httpGetRequest("https://www.baidu.com");
    }

    private static CloseableHttpClient getHttpClient() {
        try {
            KeyStore trustStore = null;
//            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            FileInputStream inputStream = new FileInputStream(new File(keyStorePath));
//            trustStore.load(inputStream, keyStorePwd.toCharArray());
            // 相信自己的CA和所有自签名的证书
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            // 设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslConnectionSocketFactory)
                    .build();
            initHttpClientConnectionManager(socketFactoryRegistry);
            return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void initHttpClientConnectionManager(Registry<ConnectionSocketFactory> registry) {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
            RequestConfig.Builder configBuilder = RequestConfig.custom();
            // 设置连接超时
            configBuilder.setConnectTimeout(MAX_TIMEOUT);
            // 设置读取超时
            configBuilder.setSocketTimeout(MAX_TIMEOUT);
            // 设置从连接池获取连接实例的超时
            configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
            // 在提交请求之前 测试连接是否可用
            configBuilder.setStaleConnectionCheckEnabled(true);
            requestConfig = configBuilder.build();
        }
    }


    /**
     * @param url
     * @return
     */
    public static String httpGetRequest(String url) {
        HttpGet httpGet = new HttpGet(url);
        if (StringUtils.isNotBlank(url)) {
            return getResult(httpGet);
        }
        return null;
    }

    public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        List<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        List<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }

    public static String httpPostRequest(String url) {
        HttpPost httpPost = new HttpPost(url);
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }

        List<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

        return getResult(httpPost);
    }

    private static List<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }

        return pairs;
    }

    private static String getResult(HttpRequestBase request) {
        if (httpClient == null) {
            httpClient = getHttpClient();
        }
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // long len = entity.getContentLength();// -1 表示长度未知
                String result = EntityUtils.toString(entity);
                response.close();
                return result;
            }
        } catch (ClientProtocolException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return EMPTY_STR;
    }
}

https校验类

MyX509Test


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.InputStreamReader;
import java.net.URL;


public class MyX509Test {
    public static void main(String[] args) {
        try {
            httpGetRequest("https://localhost:8443/user/1");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void httpGetRequest(String url) throws Exception {

        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};

        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());

        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        // 创建URL对象
        URL myURL = new URL(url);
        // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
        HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        // 取得该连接的输入流,以读取响应内容
        InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
        // 读取服务器的响应内容并显示
        int respInt = insr.read();
        while (respInt != -1) {
            System.out.print((char) respInt);
            respInt = insr.read();
        }
    }
}

MyX509TrustManager


/**
 * 自定义信任管理器
 * <p>
 * https加密
 */

public class MyX509TrustManager implements X509TrustManager {
    X509TrustManager sunJSSEX509TrustManager;
    private static final String TRUST_MANAGER_ALGORITHM = "SunX509";
    private static final String TRUEST_PROVIDER = "SunJSSE";
    private static final String CERTS_PWD = "123123";
    private static final String FILE_PATH = "D:\\keystore/kyo.keystore";


    // 构造方法初始化证书信息
    public MyX509TrustManager() throws Exception {
        // 获得keystore实例
        KeyStore ks = KeyStore.getInstance("jks");
        // keystore文件流、密码
        ks.load(new FileInputStream(FILE_PATH), CERTS_PWD.toCharArray());
        // algorithm:加密方式
        // provider:提供者
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TRUST_MANAGER_ALGORITHM, TRUEST_PROVIDER);
        // 信任管理器初始化证书
        tmf.init(ks);
        TrustManager[] tms = tmf.getTrustManagers();
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                sunJSSEX509TrustManager = (X509TrustManager) tm;
                return;
            }
        }

        // 如果都没有发现,抛出异常
        throw new Exception("Couldn'tinitialize!");
    }


    // 检测客户端是否信任程序

    public void checkClientTrusted(X509Certificate[] chain, String authType) {
        try {
            sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
        } catch (CertificateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // 检测服务器端是否信任程序
    public void checkServerTrusted(X509Certificate[] chain, String authType) {
        try {
            sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
        } catch (CertificateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 获得信任的发型证书
    public X509Certificate[] getAcceptedIssuers() {
        return sunJSSEX509TrustManager.getAcceptedIssuers();
    }

}

spring boot SSL

application.yml

server:
  port: 8443
  tomcat:
    max-connections: 2000
    max-threads: 200
    uri-encoding: UTF-8
#  ssl:
#    key-alias: tomcat
#    key-password: tomcat
#    enabled: true
#    key-store: d:\tomcat.keystore
  ssl:
    key-alias: zlf
    key-password: 111111
    enabled: true
    key-store: classpath:zlf.keystore

Application


@SpringBootApplication
public class Application {
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }

    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8000);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

keytool命令

//生成keystore
keytool -genkeypair -alias "zlf" -keyalg "RSA" -keystore "zlf.keystore"  

keytool -genkeypair -alias "kyo" -keyalg "RSA" -keystore "kyo.keystore"  

//查看keystore
keytool -list -keystore test.keystore  
//详细
keytool -list -keystore test.keystore -v

//导出证书
keytool -export -alias zlf -keystore zlf.keystore -storepass 111111 -rfc -file zlf.cer

//导入证书
keytool -import -keystore d:/keystore/kyo.keystore -file d:/keystore/zlf.cer
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot中使用HttpClient调用第三方HTTPS接口,并忽略SSL证书验证,可以通过以下步骤来实现: 1. 导入HttpClient和SSL相关的依赖: 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>javax.net.ssl</groupId> <artifactId>javax.net.ssl.HttpsURLConnection</artifactId> <version>1.0.0</version> </dependency> ``` 2. 创建忽略SSL验证的HttpClient对象: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class HttpClientUtil { public HttpClient createIgnoreSSLHttpClient() throws Exception { SSLContext sslContext = SSLContext.getInstance("TLS"); X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } }; sslContext.init(null, new TrustManager[]{trustManager}, null); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); RequestConfig reqConfig = RequestConfig.custom().setSocketTimeout(120 * 1000).setConnectTimeout(120 * 1000).build(); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setDefaultRequestConfig(reqConfig).build(); return httpClient; } } ``` 3. 使用创建的HttpClient对象发送HTTPS请求: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; public class HttpsClientExample { public static void main(String[] args) throws Exception { HttpClientUtil httpClientUtil = new HttpClientUtil(); CloseableHttpClient httpClient = (CloseableHttpClient) httpClientUtil.createIgnoreSSLHttpClient(); HttpGet httpGet = new HttpGet("https://example.com/api"); CloseableHttpResponse response = httpClient.execute(httpGet); String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(responseBody); response.close(); httpClient.close(); } } ``` 以上就是使用Spring Boot中的HttpClient实现忽略SSL证书的步骤。总结起来,主要包括导入相关依赖,创建忽略SSL验证的HttpClient对象,以及使用该对象发送HTTPS请求。 ### 回答2: Spring Boot中使用HttpClient调用第三方HTTPS接口时,如果忽略SSL证书验证,可以按照以下方法进行操作。 首先,需要在Spring Boot的配置文件application.properties中添加以下配置: ```plaintext # 忽略SSL证书验证 spring.main.allow-bean-definition-overriding=true ``` 然后,创建一个自定义的HttpClientConfig类,用于配置并创建HttpClient对象: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.net.ssl.SSLContext; @Configuration public class HttpClientConfig { @Value("${httpclient.ssl.ignore-ssl}") private boolean ignoreSSL; @Bean @ConditionalOnProperty(name = "httpclient.ssl.ignore-ssl", havingValue = "true") public HttpClient httpClient() throws Exception { if (ignoreSSL) { SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial((chain, authType) -> true) .build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); return HttpClients.custom() .setSSLSocketFactory(sslConnectionSocketFactory) .setDefaultRequestConfig(requestConfig()) .build(); } else { return HttpClients.createDefault(); } } private RequestConfig requestConfig() { return RequestConfig.custom() .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); } } ``` 最后,在需要调用第三方HTTPS接口的地方注入HttpClient对象,并使用该对象进行接口调用即可: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class HttpService { @Autowired private HttpClient httpClient; public String getResponse(String url) throws Exception { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); return EntityUtils.toString(httpResponse.getEntity()); } } ``` 以上就是使用Spring Boot的HttpClient调用第三方HTTPS接口并忽略SSL证书验证的方法。请注意,忽略SSL证书验证可能存在安全风险,建议在生产环境中谨慎使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值