【随手记录】关于FeignClient发https请求

 

默认情况下FeignClient是发http请求的,对于向类似Google这些网站发请求时候,可以不加https也支持,但是对于自己的小网站需要加证书双向验证的 需要改造FeignClient的配置类

import feign.Client;
import feign.Feign;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * Feign配置,使其支持https
 */
@Configuration
public class FeignHttpsConfig {

    @Bean
    public Feign.Builder feignBuilder() {
        final Client trustSSLSockets = client();
        return Feign.builder().client(trustSSLSockets);
    }

    public static SSLSocketFactory feignTrustingSSLSocketFactory = null;

    @Bean
    public Client client() {
        if(feignTrustingSSLSocketFactory==null){
            try {
                feignTrustingSSLSocketFactory = getFeignTrustingSSLSocketFactory();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Client client= new Client.Default(feignTrustingSSLSocketFactory, new NoopHostnameVerifier());
        return client;
    }

    public static SSLSocketFactory getFeignTrustingSSLSocketFactory() throws Exception {
        // 密码
        String passwd = "123456";
        String keyStoreType = "PKCS12";
        // 读取证书
        InputStream inputStream = null;
        SSLContext sslContext = SSLContext.getInstance("SSL");
        try {
            // 加载证书地址
            inputStream = FeignHttpsConfig.class.getResourceAsStream("/ssl/bzkjclient.key.p12");
            // 加密密钥和证书的存储工具 对象
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(inputStream, passwd.toCharArray());
            sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, passwd.toCharArray()).build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sslContext.getSocketFactory();
    }
}

之后调整FeignClient的configuration值即可

@FeignClient(name = "cloud-paltform", url = "https://xxx:9999", configuration = {FeignHttpsConfig.class})

 

上一篇:idea环境下-使用java下载网页-爬取网页


下一篇:直接下载SpringBoot项目本地的Excel文件