Springboot單體架構http請求轉換https請求來支持微信小程序調用接口

http請求轉換https請求

1、話不多說,直接上代碼!

application.properties配置文件

配置證書信息
#(密鑰文件路徑,也可以配置絕對路徑)
server.ssl.key-store= classpath:證書文件名.pfx
#(密鑰生成時輸入的密鑰庫口令)
server.ssl.key-store-password:123456
#(密鑰類型,與密鑰生成命令一致)
server.ssl.key-store-type:PKCS12

證書一般最好放在resources目錄下

接下來配置啓動類RUN.java的代碼

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;

@SpringBootApplication
@EnableTransactionManagement
@EnableScheduling
public class Run{
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Run.class, args);
    }
    

    /**
     * it's for set http url auto change to https
     */
    @Bean
    public EmbeddedServletContainerFactory servletContainer(){
        TomcatEmbeddedServletContainerFactory tomcat=new TomcatEmbeddedServletContainerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint=new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");//confidential
                SecurityCollection collection=new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
        return tomcat;
    }
    
    /**
     * 讓我們的應用支持HTTP是個好想法,但是需要重定向到HTTPS,
     * 但是不能同時在application.properties中同時配置兩個connector,
     * 所以要以編程的方式配置HTTP connector,然後重定向到HTTPS connector
     * @return Connector
     */
    private Connector initiateHttpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8084); // http端口(請求訪問時的端口)
        connector.setSecure(false);
        connector.setRedirectPort(8444); // application.properties中配置的https端口
        return connector;
    }
}

以上代碼直接拿走,接下來啓動測試

可以訪問 http端口,也可訪問 https 端口
在這裏插入圖片描述

最後附上一個小編犯的錯

把代碼打包到服務器了卻總是不能訪問,後來才發現是忘記配置服務器端口號的白名單,只需放通那個端口號就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章