1.创建工厂类并继承SimpleClientHttpRequestFactory
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.cert.X509Certificate;
/**
* @program: approval-service
* @description: https请求
* @author: wangs
* @create: 2022-07-25 15:17
*/
public class HttpsClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.注入RestTemplate后调用并设置工厂对象
@Autowired RestTemplate restTemplate;
HttpHeaders httpHeaders = new HttpHeaders();
MediaType contentType = MediaType.parseMediaType("application/json;charset=UTF-8");
httpHeaders.setContentType(contentType);
HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(params,httpHeaders);
restTemplate.setRequestFactory(new HttpsClientHttpRequestFactory());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
@Override
protected boolean hasError(HttpStatus statusCode) {
if(statusCode.series() != HttpStatus.Series.SUCCESSFUL){
throw new BusinessException("请求错误");
}else{
return false;
}
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
JSONObject resultObj = restTemplate.postForObject(url, objectHttpEntity, JSONObject.class);