Search code examples
okhttphttp2

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


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]


Solution

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