feign 调用https
时间: 2023-09-25 09:10:44 浏览: 114
Java探索之Feign入门使用详解
要使用Feign调用HTTPS接口,需要在Feign的配置中启用HTTPS支持。具体步骤如下:
1. 引入Feign的依赖
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
```
2. 配置Feign的HTTPS支持
```
@Configuration
public class FeignConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Client feignClient() {
return new Client.Default(getSSLSocketFactory(), null);
}
private SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
} }, new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(messageConverters));
}
}
```
其中,`getSSLSocketFactory`方法返回一个`SSLSocketFactory`对象,用于创建HTTPS连接。这里采用了忽略证书的方式,实际生产环境中应该使用可信的证书。
3. 在Feign的接口中使用`https`协议
```
@FeignClient(name = "example", url = "https://example.com")
public interface ExampleClient {
@GetMapping("/api")
String get();
}
```
其中,`url`参数指定了HTTPS协议的地址。
这样就可以使用Feign调用HTTPS接口了。
阅读全文