Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP/2 with OkHttp

Tags:

http2

okhttp

I am trying to communicate with a HTTP/2 server using OkHttp client.

Added to Maven POM:

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.2.0</version>
</dependency>    

And this is my test code:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://http2.akamai.com/demo").build();
Response response = client.newCall(request).execute();
System.out.println("Protocol: " + response.protocol());
System.out.println(response.body().string());

But when I run it it prints:

Protocol: http/1.1

and

This browser is not HTTP/2 enabled.

Environment: OpenJDK 8 on Linux.

Do you need something additional? I saw something called "ALPN" but did not quite understand the concept.

like image 651
holmis83 Avatar asked May 20 '16 12:05

holmis83


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.

Does Curl support http2?

curl supports http2 over standard TCP via the Upgrade: header. If you do an HTTP request and ask for HTTP 2, curl will ask the server to update the connection to http2 if possible.

Where is OkHttp used?

As of Android 5.0, OkHttp is part of the Android platform and is used for all HTTP calls.

Is OkHttp fast?

Results show that OkHttp achieves slightly better performance when compared with HttpURLConnection for transfers of larger files, by transferring the same file almost 100ms faster on a smartphone and 500ms faster in the emulator.


1 Answers

ALPN is required for HTTP/2, but it isn’t available in desktop Java until JDK 9. In Java 7 and Java 8 you’ll need a hack called jetty-alpn to enable it.

(For Java 9 there’s ALPN on the platform but only in the upcoming OkHttp 3.3.)

like image 73
Jesse Wilson Avatar answered Sep 28 '22 08:09

Jesse Wilson