使用RestTemplate调用https请求时跳过ssl证书校验

1、所需jar包(cv即可)
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.0.7.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-jaxb-annotations</artifactId>
      <version>2.9.5</version>
    </dependency>
2、枚举类(仅作为demo使用)
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName TestEnum 
 * @Description TOD0
 * author yt
 * Date 2021/03/28 16:04
 * Version 1.0
 **/
public enum TestEnum {
  //请求的url
  URL("url","https://www.test.cn/testWxApi"), // 换成自己需要调用的url
  //需要调用的接口名
  ACTION("action","testMethod"),
  //授权密钥
  ACCESSKEY("accesskey","123456"),
  //当前时间
  TIMESTAMP("timestamp",new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())),
  //随机数uuid
  RANDNUM("randnum", UUID.randomUUID().toString().replaceAll("-","")),
  //单位 18 位“统一社会信用代码
  UNIFIEDORGCODE("unifiedOrgCode","123456789ABCDEFGHI");

  private String key;
  private String value;

  WxTokenEnum(String key, String value) {
    this.key = key;
    this.value = value;
  }

  WxTokenEnum() {
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
}
3、使用RestTemplate进行调用
		String url = TestEnum.URL.getValue();
		//自定义所需参数(根据自己的需求进行更改)
        Map<String, Object> map = new HashMap<>();
        map.put(TestEnum.ACTION.getKey(), TestEnum.ACTION.getValue());
        map.put(TestEnum.ACCESSKEY.getKey(), TestEnum.ACCESSKEY.getValue());
        map.put(TestEnum.TIMESTAMP.getKey(), TestEnum.TIMESTAMP.getValue());
        map.put(TestEnum.RANDNUM.getKey(), TestEnum.RANDNUM.getValue());
        map.put(TestEnum.UNIFIEDORGCODE.getKey(), TestEnum.UNIFIEDORGCODE.getValue());
        log.info("请求入参" + map);

        RestTemplate restTemplate = new RestTemplate(new SSL());
        String json = JSON.toJSONString(map);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        //添加token到header
        //headers.add("Authorization","123456");
        HttpEntity<String> stringHttpEntity = new HttpEntity<>(json, headers);
        String result = Objects.requireNonNull(restTemplate.postForObject(url, stringHttpEntity, String.class));
        log.info("出参{}" + result);
        TokenResponse response = JSON.parseObject(result, TokenResponse.class);
4、SSL类
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;

/**
 * @ClassName SSL
 * @Description TOD0
 * author yt
 * Date 2021/03/28 16:04
 * Version 1.0
 * 跳过证书验证封装
 */
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) {
        }

    }
}

5、出参TokenResponse类
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @ClassName TokenRes
 * @Description TOD0
 * author yt
 * Date 2021/3/28 13:58
 * Version 1.0
 **/
@Data
@Accessors(chain = true)
public class TokenResponse implements Serializable {
    private static final long serialVersionUID = 1088808342309053347L;
    /**
     * msg : 操作成功
     * code : 200
     * data : {"access_token":"111111"}
     */

    private String msg;
    private int code;
    private DataBean data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public DataBean getData() {
        return data;
    }

    public void setData(DataBean data) {
        this.data = data;
    }

    public static class DataBean implements Serializable{
        private static final long serialVersionUID = -9202100583310870713L;

        private String access_token;

        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }
    }
}

你可能感兴趣的:(Java,java,spring)