https协议类型的接口忽略SSL验证

 方式一:

在终端使用CURL进行验证,需要在curl后面加上-k(-k就是忽略SSL验证)

curl -k --location --request POST 'https://XXXXXXX:8080/v1/hello' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
-d '{"userName": "hello","password": "world"}'

具体的java代码如下:

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Pattern;

public class CURLHttpUtil {

    protected static Logger logger = LoggerFactory.getLogger(CURLHttpUtil.class);
    
    public static String doPost(String url,String jsonParam,Map<String,String> headerMap){
        List<String> listCMDS = getPostRequestCMDS(url, jsonParam, headerMap);
        return replaceSpecialStr(execCurl(listCMDS.toArray(new String[]{})));
    }

    private static String execCurl(String[] cmds) {
        ProcessBuilder process = new ProcessBuilder(cmds);
        logger.debug("execCurl cmds: {}", Arrays.toString(cmds));
        Process p = null;
        BufferedReader br = null;
        try {
            p = process.start();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line).append(System.getProperty("line.separator"));
            }
            logger.debug("execCurl().builder:{}", builder.toString());
            return builder.toString();
        } catch (IOException e) {
            logger.error("execute curl command error! cmds: {}", Arrays.toString(cmds),e);
        }finally {
            if(p != null){
                p.destroy();
                logger.debug("the process closed!");
            }
            if(br != null){
                try {
                    br.close();
                    logger.debug("the bufferedReader closed!");
                } catch (IOException e) {
                    logger.error("bufferedReader closed error! ",e);
                }
            }
        }
        return null;
    }
    
    private static List<String> getPostRequestCMDS(String url, String jsonParam, Map<String, String> headerMap) {
        List<String> listCMDS = new ArrayList<>();
        listCMDS.add("curl");
        //是否绕过SSL验证,非prod环境需要跳过
        listCMDS.add("-k");
        listCMDS.add("--connect-timeout");
        listCMDS.add("25");
        listCMDS.add("--max-time");
        listCMDS.add("25");
        listCMDS.add("--location");
        listCMDS.add("POST");
        listCMDS.add(url);
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            listCMDS.add("--header");
            listCMDS.add(entry.getKey() + ":" + entry.getValue());
        }
        listCMDS.add("--data-raw");
        listCMDS.add(jsonParam);
        return listCMDS;
    }

    private static String replaceSpecialStr(String str) {
        return StringUtils.isEmpty(str) ? null : str.replaceAll("\\s*|\t|\r|\n", "");
    }

    private static boolean isInteger(String str) {
        return Objects.nonNull(str) && Pattern.compile("^[-+]?[\\d]*$").matcher(str).matches();
    }
}

方式二:

使用jdk自带的javax.net.ssl.HttpsURLConnection

package cn.gt.isc.interm.web.utils.im;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.*;
import javax.ws.rs.HttpMethod;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class HttpUtil {
    private static final Map<String,Boolean> IGNORE_URL_SSL_MAP = new HashMap<>();

    private static final int READ_TIME_OUT = 5000;

    private static final int CONNECT_TIME_OUT = 2000;

    /**
     *
     * @param serviceAddress 服务地址,例如https://www.baidu.com
     * @param uri            接口uri,例如/v1/hello
     * @param paramsMap      请求参数
     * @param headers        请求头参数
     * @return
     */
    public static String jsonPost(String serviceAddress,String uri, Map<String,Object> paramsMap, Map<String,String> headers) {
        HttpsURLConnection httpsURLConnection;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        OutputStream out = null;
        try {
            URL reqUrl = new URL(serviceAddress + uri) ;
            //忽略ssl验证
            ignoreSsl(serviceAddress);

            httpsURLConnection = (HttpsURLConnection) reqUrl.openConnection();
            httpsURLConnection.setRequestMethod(HttpMethod.POST);
            httpsURLConnection.setReadTimeout(READ_TIME_OUT);
            httpsURLConnection.setConnectTimeout(CONNECT_TIME_OUT);

            //设置是否向HttpURLConnection输出
            httpsURLConnection.setDoOutput(true);
            //设置是否从HttpUrlConnection读入,默认为true
            httpsURLConnection.setDoInput(true);
            //设置是否使用缓存
            httpsURLConnection.setUseCaches(false);

            if (! CollectionUtils.isEmpty(headers)) {
                headers.forEach(httpsURLConnection::setRequestProperty);
            }
            //建立连接
            httpsURLConnection.connect();
            //写入请求数据
            out = httpsURLConnection.getOutputStream();
            out.write(JSONObject.toJSONString(paramsMap).getBytes());
            out.flush();
            if (httpsURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpsURLConnection.getInputStream();
                byteArrayOutputStream = new ByteArrayOutputStream();
                int len = 0;
                byte[] bytes = new byte[512];
                while ((len = inputStream.read(bytes)) != -1) {
                    byteArrayOutputStream.write(bytes, 0, len);
                }
                return byteArrayOutputStream.toString();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(Objects.nonNull(out)){
                try {
                    out.close();
                } catch (Exception ignored) {
                }
            }
            if(Objects.nonNull(inputStream)){
                try {
                    inputStream.close();
                } catch (Exception ignored) {

                }
            }
            if(Objects.nonNull(byteArrayOutputStream)){
                try {
                    byteArrayOutputStream.close();
                } catch (Exception ignored) {

                }
            }
        }
        return null;
    }

    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new CustomTrustManager();
        trustAllCerts[0] = tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    /**
     * 忽略HTTPS请求的SSL证书,这里做了dubbo check,防止重复调用
     */
    private static void ignoreSsl(String serviceAddress) throws Exception {
        if(IGNORE_URL_SSL_MAP.getOrDefault(serviceAddress,false)){
            return;
        }
        synchronized (HttpUtil.class){
            if(IGNORE_URL_SSL_MAP.getOrDefault(serviceAddress,false)){
                return;
            }
            HostnameVerifier hv = (urlHostName, session) -> true;
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            IGNORE_URL_SSL_MAP.put(serviceAddress,true);
        }
    }

    private static class CustomTrustManager implements TrustManager, X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {

        }

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

        }
    }
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Spring Boot 中,可以通过配置忽略 SSL 验证来访问 HTTPS 资源。但是,忽略 SSL 验证会降低网络安全性,因此只有在特殊情况下才应该使用该方法。 以下是一个示例,展示了如何在 Spring Boot 中忽略 SSL 验证: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import javax.net.ssl.*; import java.security.cert.X509Certificate; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() throws Exception { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }}; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(requestFactory); return restTemplate; } } ``` 这个示例中,我们创建了一个 RestTemplate bean,并通过配置 SSLContext 来忽略 SSL 验证。在 SSLContext 中,我们将信任所有的证书,并设置了默认的 SSL socket 工厂和主机名验证器。 请注意,在使用这种方法之前,你应该了解忽略 SSL 验证可能带来的风险,并确保在生产环境中使用 HTTPS 时启用了正确的 SSL 验证

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

燕少༒江湖

给我一份鼓励!谢谢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值