简体   繁体   中英

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

I am getting below exception, in response of https rest service call through OkHttpClient

I am using library com.squareup.okhttp3:okhttp-ws:3.4.2.

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection? at sun.security.ssl.InputRecord.handleUnknownRecord(Unknown Source)

        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();

When I use http URL, it's sending https URL to interacting application. But in log also, I am printing before executing call, it's showing http URL only

I need to make it work with https URL.

Let me know in case any other information required.

You are accidentally passing in an sslSocketFactory into socketFactory.

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

You want

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

You must be using a really old version of OkHttp as this is specifically checked for for multiple years.

    /**
     * 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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM