Openfeign和okHttp的https请求忽略ssl证书认证

这篇具有很好参考价值的文章主要介绍了Openfeign和okHttp的https请求忽略ssl证书认证。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在通过feign和okhttp请求外部接口时,出现了以下问题:

Servlet.service() for servlet [dispatcherServlet] in context with path [/xxxx] threw exception [Request processing failed; nested exception is feign.RetryableException: java.security.cert.CertificateException: No subject alternative DNS name matching www.xx.xx.cn found. executing GET https://xxxxxx] with root cause
java.security.cert.CertificateException: No subject alternative DNS name matching bisp.eshore.cn found.

因为我调用的接口是https接口。 要么就导入证书,要么就忽略证书验证。下面记录的是忽略证书验证的方法:

feign忽略ssl认证的方法:

import feign.Client;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


public class IgnoreFeignHttpsSSLClient {
    public Client feignClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("SSL");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            return new Client.Default(ctx.getSocketFactory(), (hostname, session) -> true);
        } catch (Exception e) {
            return null;
        }
    }
}

1.通过初始化SearchClient的方式调用feign接口的方法:

// SearchClient Feign接口调用构建初始化
@Configuration
public class FeignConfig {
	@Bean
	public SearchClient searchClient(IgnoreHttpsSSLClient ignoreHttpsSSLClient) {
	    return Feign.builder()
	       .encoder(new JacksonEncoder())
	       .decoder(new JacksonDecoder())
	       .logLevel(Logger.Level.FULL)
	       .logger(new Slf4jLogger(SearchClient.class))
	       .client(new IgnoreFeignHttpsSSLClient().feignClient())
	       .options(new Request.Options(60000, 60000))
	       .target(SearchClient.class, "https://10.25.193.111:443/");
	}
}

2.通过@feignClient注解的方式调用:

@Configuration
public class ServiceFeignConfiguration {

    // 加载自定义Client
    @Bean
    public Client generateClient() {
        return new IgnoreFeignHttpsSSLClient().feignClient();
    }

}
@FeignClient(value = "testFeignClient", url = "https://wwww.xxx.xxx.cn/", configuration = ServiceFeignConfiguration.class)
public interface TestFeignClient {
	@RequestLine("POST /testPost")
    JSONObject testPost();
}

okhttpclent忽略ssl证书的方式:

 <dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>3.8.1<version>
</dependency>
private static OkHttpClient okHttpClient = null;

    static {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addNetworkInterceptor(logInterceptor)
                .sslSocketFactory(getSSLSocketFactory(),  getX509TrustManager())
                .hostnameVerifier(getHostnameVerifier())
                .build();
    }


     /**
      * description 忽略https证书验证
      */
    private static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
    /**
     * description 忽略https证书验证
     */
    private static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }

    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

后续就可以直接调用该接口了:文章来源地址https://www.toymoban.com/news/detail-733663.html

public static String get(String url, Map<String, String> header, Map<String, String> query){

        String returnStr = null;
        // 创建一个请求 Builder
        Request.Builder builder = new Request.Builder();
        // 创建一个 request
        Request request = builder.url(url).build();

        // 创建一个 HttpUrl.Builder
        HttpUrl.Builder urlBuilder = request.url().newBuilder();
        // 创建一个 Headers.Builder
        Headers.Builder headerBuilder = request.headers().newBuilder();
        if (header != null) {
            // 装载请求头参数
            Iterator<Map.Entry<String, String>> headerIterator = header.entrySet().iterator();
            headerIterator.forEachRemaining(e -> {
                if (e.getValue() != null) {
                    headerBuilder.add(e.getKey(), (String) e.getValue());
                }
            });
        }

        if (query != null) {
            // 装载请求的参数
            Iterator<Map.Entry<String, String>> queryIterator = query.entrySet().iterator();
            queryIterator.forEachRemaining(e -> {
                if (e.getValue() != null) {
                    urlBuilder.addQueryParameter(e.getKey(), (String) e.getValue());
                }
            });
        }

        // 设置自定义的 builder
        builder.url(urlBuilder.build()).headers(headerBuilder.build());

        try {
            Response execute = okHttpClient.newCall(builder.build()).execute();
            returnStr = execute.body().string();
        } catch (IOException e) {
            LOGGER.error("接口请求异常:"+ url, e);
        }
        return returnStr;
    }

到了这里,关于Openfeign和okHttp的https请求忽略ssl证书认证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包