https接口调用忽略SSL证书

该博客介绍了如何在Java中使用RestTemplate和HttpClient工具类进行HTTPS请求,并在必要时忽略SSL证书检查。通过创建不安全的SSLContext和TrustManager,可以实现对HTTPS连接的信任所有证书。此外,还展示了如何设置代理和超时时间。这些方法适用于需要快速原型验证或处理自签名证书的场景。
摘要由CSDN通过智能技术生成

restTemplate方式

工具类HttpsClientUtils

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @params
 * @return        
 * @method  Https 调用忽略 SSL
 * @description
 * @author XXXX 
 * @date 2021/11/16 16:26
 */
public class HttpsClientUtils {

    public static RestTemplate getInstance(Proxy proxy, int connTimeout, int readTimeout, boolean enableSslCheck) {
        final RestTemplate restTemplate = new RestTemplate();

        // sslIgnore
        SimpleClientHttpRequestFactory requestFactory;
        if (!enableSslCheck) {
            requestFactory = getUnsafeClientHttpRequestFactory();
        } else {
            requestFactory = new SimpleClientHttpRequestFactory();
        }

        // proxy
        if (proxy != null) {
            requestFactory.setProxy(proxy);
        }

        // timeout
        requestFactory.setConnectTimeout(connTimeout);
        requestFactory.setReadTimeout(readTimeout);

        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }

    private static SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {

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

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

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        final SSLContext sslContext;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(e);
        }

        return new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection,
                                             @NotNull String httpMethod) throws IOException {
                super.prepareConnection(connection, httpMethod);
                if (connection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) connection).setSSLSocketFactory(
                            sslContext.getSocketFactory());
                }
            }
        };
    }

    public static RestTemplate getInstance(Proxy proxy, boolean enableSsLCheck) {
        return getInstance(proxy, -1, -1, enableSsLCheck);
    }

}

在代理中使用

@Slf4j
@Component("proxy.jflhtoken")
public class TokenHandler extends ProxyHandler {

    @Override
    protected MultiValueMap<String, Object> encodeParam(String serialno, JSONObject config, MultiValueMap<String, Object> param) throws FailException, ProxyException {
        return param;
    }

    @Override
    protected String excute(YwztProxy proxy, JSONObject config, MultiValueMap<String, Object> param) throws ProxyException, FailException {
        //Https调用忽略 SSL
        RestTemplate restTemplateToken =  HttpsClientUtils.getInstance(null,false);
        HttpHeaders headersToken = new HttpHeaders();
        headersToken.add("Content-Type", MediaType.APPLICATION_JSON.toString());
        headersToken.add("X-Requested-With", "XMLHttpRequest");
        JSONObject jsonObject = new JSONObject();
        if (!StringUtils.isEmpty(config.get("username")))
            jsonObject.put("username", config.get("username").toString());
        if (!StringUtils.isEmpty(config.get("password")))
            jsonObject.put("password", config.get("password").toString());
        HttpEntity requestEntityToken = new HttpEntity(jsonObject.toJSONString(), headersToken);
        ResponseEntity<String> responseEntityToken = restTemplateToken.postForEntity(proxy.getUrl(), requestEntityToken, String.class);
        return responseEntityToken.getBody();
    }

    @Override
    protected String decodeResult(String serialno, JSONObject config, String resultString) {
        return resultString;
    }
}

httpClient方式

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class TestHTTPS {

    private static Logger logger = LoggerFactory.getLogger(TestHTTPS.class);

    public static void main(String[] args) {
        HttpHeaders headersToken = new HttpHeaders();
        headersToken.add("Content-Type", MediaType.APPLICATION_JSON.toString());
        headersToken.add("X-Requested-With", "XMLHttpRequest");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "ASDXDDDSSDDDDSS");
        jsonObject.put("password", "BDDDDDDDDDDDDDD");
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
            String url = "https://qew.ee.ty.hy.cn/tip/api/login";
            httpClient = createIgnoreSSLHttpClient();
            if (httpClient == null) {
                logger.error("HttpClient create fail.");
                return;
            }
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("utf-8")));
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                System.out.println("NO_OK : " + null);
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("OK : " + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static CloseableHttpClient createIgnoreSSLHttpClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值