RestTemplate 请求htts接口

原理

通过忽略对证书的校验而信任所有的链接

工具类

import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyStore;

public class HttpsClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        try {
            if (connection instanceof HttpsURLConnection) {// https协议,修改协议版本
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                // 信任任何链接,忽略对证书的校验
                TrustStrategy anyTrustStrategy = (x509Certificates, s) -> true;
                //自定义SSLContext
                SSLContext ctx = SSLContexts.custom().loadTrustMaterial(trustStore, anyTrustStrategy).build();
                // ssl问题
                ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                //解决No subject alternative names matching IP address xxx.xxx.xxx.xxx found问题
                ((HttpsURLConnection) connection).setHostnameVerifier((s, sslSession) -> true);
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                super.prepareConnection(httpsConnection, httpMethod);
            } else { // http协议
                super.prepareConnection(connection, httpMethod);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

调用层

	RestTemplate restTemplate = new RestTemplateBuilder()
                .requestFactory(HttpsClientHttpRequestFactory::new)
                //basic认证
                .build();
 // 设置请求头信息
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);
// 将参数转化为JSON字符串
	String jsonString =JSONObject.toJSONString(dataDto);
	HttpEntity<String> entity = new HttpEntity<>(jsonString,headers);
// 调用接口 	URL 请求的https接口,
	ResponseEntity<JSONObject> response = restTemplate.exchange(URL, HttpMethod.POST, entity, JSONObject.class);

JSONObject jsonObject = response.getBody();
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐