java springboot发送https请求

1.通常我们调用第三方接口api项目中引入

@Autowired
private RestTemplate restTemplate;

这种方式https请求被拒绝

2.解决方案

通过ssl配置项重新new出对象 加入两行代码


    @Autowired
    private RestTemplate restTemplate;
    private static RestTemplate restTemplates = new RestTemplate(new SSL());

ssl配置类继承SimpleClientHttpRequestFactory重新方法

package com.bzfar.config;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @Auther Ethons
 * @Date 2021/11/2
 */
public class SSL extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod)
            throws IOException {
        if (connection instanceof HttpsURLConnection) {
            prepareHttpsConnection((HttpsURLConnection) connection);
        }
        super.prepareConnection(connection, httpMethod);
    }

    private void prepareHttpsConnection(HttpsURLConnection connection) {
        connection.setHostnameVerifier(new SkipHostnameVerifier());
        try {
            connection.setSSLSocketFactory(createSslSocketFactory());
        }
        catch (Exception ex) {
            // Ignore
        }
    }

    private SSLSocketFactory createSslSocketFactory() throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new SkipX509TrustManager() },
                new SecureRandom());
        return context.getSocketFactory();
    }

    private class SkipHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }

    }

    private static class SkipX509TrustManager implements X509TrustManager {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

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

    }
}

Spring Boot发送HTTPS POST请求,需要进行如下步骤: 1. 创建SSLContext对象 ```java private SSLContext createSSLContext() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream inputStream = getClass().getResourceAsStream("/keystore.jks"); keyStore.load(inputStream, "password".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "password".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; } ``` 2. 创建HttpClient对象 ```java private CloseableHttpClient createHttpClient() throws Exception { SSLContext sslContext = createSSLContext(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); } ``` 3. 发送POST请求 ```java private void sendPostRequest() throws Exception { String url = "https://example.com/api"; HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); String requestBody = "{\"key\":\"value\"}"; httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); CloseableHttpClient httpClient = createHttpClient(); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println(responseBody); } } ``` 在以上代码中,我们首先创建了一个SSLContext对象,该对象使用JKS格式的证书库,加载了我们的证书文件,并使用KeyManagerFactory和TrustManagerFactory初始化了SSLContext对象。 接着,我们创建了一个HttpClient对象,该对象使用我们之前创建的SSLContext对象,同时指定了TLSv1.2协议,以及默认的主机名验证器。 最后,我们使用HttpClient对象发送了一个POST请求,该请求包含了请求头Content-Type为application/json,以及请求体为一个JSON字符串的实体。我们通过execute方法执行请求,并获取响应实体的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值