Java feign使用okhttp跳过https安全校验

今天调用微软Azure OpenAI时报错了,百度一番发现需要https证书,后来想能不能跳过校验呢,费心良苦实验一番终于实现

代码如下

一、添加Maven依赖

     	<dependency>
            <groupId>com.netflix.feigngroupId>
            <artifactId>feign-coreartifactId>
            <version>8.18.0version>
        dependency>
        <dependency>
            <groupId>com.netflix.feigngroupId>
            <artifactId>feign-jacksonartifactId>
            <version>8.18.0version>
        dependency>
        <dependency>
            <groupId>com.netflix.feigngroupId>
            <artifactId>feign-okhttpartifactId>
            <version>8.18.0version>
        dependency>

        <dependency>
            <groupId>com.squareup.okhttp3groupId>
            <artifactId>okhttpartifactId>
            <version>4.9.1version>
        dependency>

二、添加配置文件

azure:
  prologue: You are a helpful assistant.
  chat-gpt:
    url: https://xxxxx.com/
    key: xxxxxxx
    deployments: xxxxxx

三、添加对内调用接口

public interface AzureApiDao {

    Response sedChatByAzure(AzureChatSendMessage azureChatSendMessage);

}

四、实现层(fegin初始化,跳过校验)

@Slf4j
@Service
public class AzureApiDaoImpl implements AzureApiDao {

    private static AzureChatApi AZURE_CHAT_API;

    @Value("${azure.chat-gpt.url}")
    protected String url;

    @Value("${azure.chat-gpt.key}")
    private String key;

    @Value("${azure.chat-gpt.deployments}")
    private String deployments;


    private static SSLSocketFactory createTrustAllSslSocketFactory(TrustManager[] trustManagers) throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
        return sslContext.getSocketFactory();
    }


    @PostConstruct
    @SneakyThrows
    protected void init() {

        // 1. 创建一个不进行任何证书校验的 TrustManager
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                    public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
                }
        };

        // 2. 创建一个 OkHttpClient.Builder 对象,并将上面创建的 TrustManager 设置到 OkHttpClient.Builder 中
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .hostnameVerifier((hostname, session) -> true)
                .sslSocketFactory(createTrustAllSslSocketFactory(trustAllCerts), 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 new X509Certificate[0];
                    }
                });

        AZURE_CHAT_API = Feign.builder()
                .client(new feign.okhttp.OkHttpClient(builder.build()))
                .decoder(new Decoder.Default())
                .encoder(new JacksonEncoder())
                .errorDecoder(new ErrorDecoder.Default())
                .target(AzureChatApi.class, url);

    }

    @Override
    public Response sedChatByAzure(AzureChatSendMessage azureChatSendMessage) {


        return AZURE_CHAT_API.sendChatMessage(deployments, key, azureChatSendMessage);
    }



}

五、使用Feign调用第三方API(GET)

public interface AzureChatApi {

    /**
     * 聊天消息发送
     */

    @RequestLine("POST /openai/deployments/{deployments}/chat/completions?api-version=2023-05-15")
    @Headers({"Content-Type: application/json","api-key: {key}","Accept: application/octet-stream"})
    Response sendChatMessage(@Param("deployments") String deployments, @Param("key") String key, AzureChatSendMessage messages);

}

OK,齐活~

你可能感兴趣的:(Java,java,feign)