在通过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证书的方式:文章来源:https://www.toymoban.com/news/detail-733663.html
<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模板网!