Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force okhttp to use http/2 for a request?

Tags:

http2

okhttp

I'd like to make a request and force it to use the Protocol.HTTP_2. I tried the code below:

import okhttp3.{OkHttpClient, Protocol, Request}

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer

object Main2 extends App {
  val url = "https://google.com/"
  val client = new OkHttpClient.Builder().protocols(ListBuffer(Protocol.HTTP_2)).build()
  val request = new Request.Builder().url(url).build()
  val response = client.newCall(request).execute()
  println(response.body().string())
}

But a got the error: Exception in thread "main" java.lang.IllegalArgumentException: protocols doesn't contain http/1.1: [h2]

like image 845
Robinho Avatar asked Oct 31 '22 04:10

Robinho


2 Answers

OkHttp will automatically use HTTP/2 if it’s available, but you can’t disable HTTP/1.1.

like image 196
Jesse Wilson Avatar answered Nov 20 '22 02:11

Jesse Wilson


If you aren't using SSL/TLS you can use Protocol.H2_PRIOR_KNOWLEDGE instead of Protocol.HTTP_2 when creating the OkHttpClient.

This will send a cleartext HTTP/2 that doesn't first negotiate with the service on which protocol to use.

For me, this forces HTTP/2 when the server is multiplexing HTTP/1.1 and HTTP/2.

Source: https://square.github.io/okhttp/3.x/okhttp/okhttp3/Protocol.html#H2_PRIOR_KNOWLEDGE

like image 44
Joris Enzerink Avatar answered Nov 20 '22 01:11

Joris Enzerink