springboot 配置resttemplate跳过安全认证请求https接口
配置resttemplateconfig配置类
@configuration
public class resttemplateconfig {
@autowired
private environment env;
@bean("simpleclienthttprequestfactory")
public clienthttprequestfactory simpleclienthttprequestfactory()
throws nosuchalgorithmexception, keystoreexception, keymanagementexception {
httpcomponentsclienthttprequestfactory factory = new httpcomponentsclienthttprequestfactory();
// set connect timeout and read timeout
/**
* env.getproperty("config.resttemplate.connecttimeout")
* env.getproperty("config.resttemplate.readtimeout")
* 此处的两个变量为配置文件里所配置的,可以直接替换位两个整数
*/
factory.setconnecttimeout(numberutils.toint(env.getproperty("config.resttemplate.connecttimeout"), 5000));
factory.setreadtimeout(numberutils.toint(env.getproperty("config.resttemplate.readtimeout"), 30000));
// set sslcontext to trust all certificates (skip ssl certificate verification)
truststrategy acceptingtruststrategy = (x509certificate[] x509certificates, string authtype) -> true;
sslcontext sslcontext = sslcontexts.custom().loadtrustmaterial(null, acceptingtruststrategy).build();
sslconnectionsocketfactory connectionsocketfactory = new sslconnectionsocketfactory(sslcontext, new noophostnameverifier());
closeablehttpclient httpclient = httpclients.custom().setsslsocketfactory(connectionsocketfactory).build();
factory.sethttpclient(httpclient);
return factory;
}
@bean("sslresttemplate")
public resttemplate getresttemplate(@qualifier("simpleclienthttprequestfactory") clienthttprequestfactory requestfactory) {
return new resttemplate(requestfactory);
}
}
装配bean可以直接使用
@autowired
@qualifier("sslresttemplate")
resttemplate resttemplate;
/**
* 此处的url,以及entity都需要自行配置
* url为请求地址
* jsonstring为请求参数转换成的json字符串
*/
httpentity entity = new httpentity<>(jsonstring, getrequestheader());
responseentity<string> responseentity = resttemplate.postforentity(url, entity, string.class);
protected static httpheaders getrequestheader() {
httpheaders headers = new httpheaders();
headers.set("content-type", "application/json");
//headers.setcontenttype(mediatype.parsemediatype("application/json; charset=utf-8"));
return headers;
}
核心:在配置resttemplateconfig,让其信任所有的证书(慎用此方法)
建议:可以通过nginx跳转http请求到https请求
发表评论