当前位置: 代码网 > it编程>编程语言>Java > Springboot配置RestTemplate跳过安全认证请求https接口

Springboot配置RestTemplate跳过安全认证请求https接口

2024年08月03日 Java 我要评论
springboot跳过安全认证请求https接口

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请求

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com