java 跳过 SSL

java 跳过 SSL

先用postman 测试下,(https://xxxxxxxx.com 地址)是否能访问成功

若在postman 中设置了,关闭SSL 验证

那java 代码里需要做一定来的变更,

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/>
    </parent>
    
    <groupId>org.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

测试代码

import com.alibaba.fastjson.JSONObject;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>记录一次post访问,跳过ssl</p>
 *
 * @author YsEz
 * @version V1.0.0
 * @date 2022/5/26 14:54
 */

public class ToKenDataTest {
    protected static Logger log = LoggerFactory.getLogger(ToKenDataTest.class);

    public static void main(String[] args) {
        //uri
        String uri = "https://";
        //头
        Map<String, String> headerMap = new HashMap<>();
        //体
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("app_key", "123");
        paramMap.put("app_value", "456");
        //post 请求 获得token
        String httpPostToken = getHttpPost(uri, headerMap, paramMap);
        //
        System.out.println("---httpPostToken:" + httpPostToken);

    }

    private static String getHttpPost(String uri, Map<String, String> headerMap, Map<String, String> paramMap) {
        HttpClient httpClient = wrapClient();//创建HttpClient,关键点一
        //uri,这里决定用 post,还是用其他方式
        HttpGet httpGet = new HttpGet(uri);
        HttpPost httpPost = new HttpPost(uri);
        HttpDelete httpDelete = new HttpDelete(uri);
        HttpPut httpPut = new HttpPut(uri);
        //头
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
        //体
        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.create("application/json", "utf-8")));
        System.setProperty("jsse.enableSNIExtension", "false");//ssl免检  关键点二
        //访问
        HttpResponse httpResponse;
        String entity = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            entity = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return entity;
    }

    public static HttpClient wrapClient() {//关键点三
        try {
        	SSLContext sc = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        X509Certificate[] x509Certificates, String s) {
                }

                @Override
                public void checkServerTrusted(
                        X509Certificate[] x509Certificates, String s) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sc.init(null, new TrustManager[] {tm}, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(ssf).build();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            return HttpClients.createDefault();
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值