码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-11-16 13:39:11      阅读:16      评论:0      收藏:0      [点我收藏+]

标签:xxx   final   instance   加载   toc   get   factory   支持   keystore   

 

默认情况下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})

 

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

标签:xxx   final   instance   加载   toc   get   factory   支持   keystore   

原文地址:https://www.cnblogs.com/whaleX/p/13954985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!