OkHttpClient 将 http URL 重定向到 Https 并使用 https URL 给出 SSLException

OkHttpClient redirects http URL to Https and gives SSLException with https URL

我遇到异常,响应通过 OkHttpClient 的 https 休息服务调用

我正在使用库 com.squareup.okhttp3:okhttp-ws:3.4.2.

javax.net.ssl.SSLException: 无法识别的 SSL 消息,明文连接? 在 sun.security.ssl.InputRecord.handleUnknownRecord(来源不明)

        File certFile = resourceLoader.getResource("classpath:" + certKey).getFile();
        try {
            sslContext = SSLContextBuilder.create()
                    .loadKeyMaterial(certFile, certKeyPassword.toCharArray(), certKeyPassword.toCharArray())
                    .loadTrustMaterial(certFile, certKeyPassword.toCharArray()).build();
        SSLSocketFactory sslSocketFactory = sslContext().getSocketFactory();
        RequestBody formBody = new FormBody.Builder()
                    .add("<key>", "<value>")
                    .build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder().socketFactory(sslSocketFactory).build();
        Request request = new Request.Builder()
                    .url(https URL)
                    .post(formBody)
                    .addHeader("Content-Type", "application/json")
                    .build();
        LOG.info("Request passed: "+request);
        response = okHttpClient.newCall(request).execute();

当我使用 http URL 时,它会将 https URL 发送到交互应用程序。 但是在日志中,我也在执行调用之前打印,它只显示 http URL

我需要使用 https URL。

如果需要任何其他信息,请告诉我。

您不小心将 sslSocketFactory 传入了 socketFactory。

OkHttpClient okHttpClient = new OkHttpClient.Builder().socketFactory(sslSocketFactory).build();

你想要

OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustManager).build();

您必须使用真正旧版本的 OkHttp,因为它已经经过多年专门检查。

    /**
     * Sets the socket factory used to create connections. OkHttp only uses the parameterless
     * [SocketFactory.createSocket] method to create unconnected sockets. Overriding this method,
     * e. g., allows the socket to be bound to a specific local address.
     *
     * If unset, the [system-wide default][SocketFactory.getDefault] socket factory will be used.
     */
    fun socketFactory(socketFactory: SocketFactory) = apply {
      require(socketFactory !is SSLSocketFactory) { "socketFactory instanceof SSLSocketFactory" }

      if (socketFactory != this.socketFactory) {
        this.routeDatabase = null
      }

      this.socketFactory = socketFactory
    }