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

2

12

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]

Laciniate answered 28/4, 2016 at 1:45 Comment(0)
K
8

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

Kapp answered 28/4, 2016 at 4:35 Comment(1)
It doesn't seem to work if my server is multiplexing HTTP/1.1 and HTTP/2Gyre
H
5

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

Hollington answered 30/8, 2021 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.