okhttpclient将http url重定向到https,并使用https url提供sslexception

ux6nzvsh  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(487)

我得到以下异常,通过okhttpclient响应https rest服务调用
我正在使用库com.squareup.okhttp3:okhttpws: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();

当我使用HTTPURL时,它将https url发送到交互应用程序。但在日志中,我也在执行调用之前打印,它只显示httpurl
我需要使它与https网址工作。
如果需要其他信息,请告诉我。

ncgqoxb0

ncgqoxb01#

您不小心将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
    }

相关问题