Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java OkHttp3 only use Http/1.1 OR Http/2

Trying to do some test-cases for HTTP requests. I want to distinguish between HTTP/1.1 and HTTP/2. In order to do that, I need to know which version I have used from a request. I also want to force the request to use HTTP/1.1 or HTTP/2. I am using OkHttp3 for Java. Here is a simple request which I do:

Request request = new Request.Builder()
            .url(url)
            .build();

Response response = client.newCall(request).execute();
return response.body().string();
like image 853
csnewb Avatar asked Jan 29 '17 20:01

csnewb


People also ask

Does OkHttp support http2?

OkHttp OverviewOkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

What is the use of OkHttp in Android?

OkHttp android provides an implementation of HttpURLConnection and Apache Client interfaces by working directly on a top of java Socket without using any extra dependencies.

What is the underlying library of OkHttp?

Beginning with Mobile SDK 4.2, the Android REST request system uses OkHttp (v3. 2.0), an open-source external library from Square Open Source, as its underlying architecture. This library replaces the Google Volley library from past releases.

What is the difference between retrofit and OkHttp?

Okio-okhttp3 is a library that works in conjunction with java.io and java. nio to make data access, storage, and processing considerably easier. It started as a component of OkHttp. Retrofit is a type-safe REST client for Java and Android application development.


1 Answers

You can force the request to be HTTP/1.1 only with the following code

new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1));

You can't force HTTP/2 only as HTTP/1.1 must be in the protocols list.

However you can confirm by checking protocol on the Response object

Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

Response response = client.newCall(request).execute();

assert(response.protocol() == Protocol.HTTP_2);
like image 51
Yuri Schimke Avatar answered Oct 19 '22 06:10

Yuri Schimke