Igor_M
Igor_M

Reputation: 338

How OkHttpClient can establish TLS connection via http2 with server that does not support ALPN?

I'm using OkHttpClient 3.14.9. I need to establish connection using TLSv1.3 and http2 protocols. The problem is that server does not support ALPN (OkHttpClient uses this extention to establish with server which version of http protocol to use).

On server side http1.1 is disabled, only http2 enabled. Client does not succeed to establish connection. When server enables http1.1, my client connects to server via http1.1.

As I understand, it means that there is no negotiation between client and server about http version: client is trying to negotiate via ALPN -> server does not "understand" client -> client think that server does not support http2 and try to connect with http1.1

So, if not ALPN, is there any other way for OkHttpClient to establish TLS connection via http2? (important that connection is TLS, because without TLS Protocol.H2_PRIOR_KNOWLEDGE works good)

Upvotes: 1

Views: 816

Answers (1)

Yuri Schimke
Yuri Schimke

Reputation: 13488

Something like the following should/could work on JDK9. But it's hard to test as it's effectively a broken server.

  val sslSocketFactory = context.socketFactory
  val wrapped = object : DelegatingSSLSocketFactory(sslSocketFactory) {
    override fun configureSocket(sslSocket: SSLSocket): SSLSocket {
      return object : DelegatingSSLSocket(sslSocket) {
        override fun getApplicationProtocol(): String {
          return "h2"
        }
      }
    }
  }

  val client = OkHttpClient.Builder()
    .sslSocketFactory(wrapped, trustManager)
    .build()

  val response = client.newCall(Request.Builder().url("https://api.twitter.com/").build()).execute()
  println(response.protocol)

You can grab the delegating socket factory here https://github.com/square/okhttp/blob/c1a6dec505a62af07e4c117e777302bd136e107f/okhttp-testing-support/src/main/kotlin/okhttp3/DelegatingSSLSocketFactory.kt

But on different JVMs, or different Android versions this may work differently.

It's the reason we have adapters for different socket types like Android10SocketAdapter.kt, ConscryptSocketAdapter.kt etc.

https://github.com/square/okhttp/blob/3ad1912f783e108b3d0ad2c4a5b1b89b827e4db9/okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/android/SocketAdapter.kt#L35

Upvotes: 1

Related Questions