Zack
Zack

Reputation: 1113

How to use http/2 with Okhttp on Android devices?

I'M testing a site that supports HTTP/2,like this, and I try to use okhttp to send the request:

OkHttpClient okHttpClient = new OkHttpClient();

Request request = new Request.Builder()
        .url("https://www.google.it")
        .build();


okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        Log.d("TestHttp", "OkHttp-Selected-Protocol: " + response.header("OkHttp-Selected-Protocol"));
        Log.d("TestHttp", "Response code is " + response.code());
    }
});

In the log I got something like this:

OkHttp-Selected-Protocol: http/1.1

The okhttpClient chose to use http/1.1, how can I force it to use HTTP/2?

Upvotes: 17

Views: 14269

Answers (2)

Firzen
Firzen

Reputation: 2095

You just need to initialize your OkHttpClient in proper way.

Kotlin:

val client = OkHttpClient().newBuilder()
    .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
    .build()

// Your client will now try to use HTTP 2 if possible. If not, then HTTP 1.1 will be used.

Java:

List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP_2);
protocols.add(Protocol.HTTP_1_1);

OkHttpClient client = new OkHttpClient.Builder()
        .protocols(protocols)
        .build();

// Your client will now try to use HTTP 2 if possible. If not, then HTTP 1.1 will be used.

If you wish to check if HTTP 2 is being used, see my other answer: https://stackoverflow.com/a/72983159/1735603

Upvotes: 2

Zack
Zack

Reputation: 1113

Okhttp 2.5+ only support http/2 above 5.0+ via ALPN.

but you can modify the source code to support http/2 above 4.0+ via NPN.

Upvotes: 5

Related Questions