Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 485
Zack Avatar asked Aug 06 '15 08:08

Zack


People also ask

Does OkHttp support http2?

OkHttp (https://square.github.io/okhttp/) is an efficient HTTP & HTTP/2 client for Android and Java applications. It's been widely used in Android and has good documentation also.

How do I use OkHttp on Android?

OkHttp Query Parameters Example Builder urlBuilder = HttpUrl. parse("https://httpbin.org/get).newBuilder(); urlBuilder. addQueryParameter("website", "www.journaldev.com"); urlBuilder. addQueryParameter("tutorials", "android"); String url = urlBuilder.

What is the use of OkHttp?

OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.


1 Answers

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.

like image 152
Zack Avatar answered Oct 05 '22 20:10

Zack