Search code examples
okhttphttp2

HTTP/2 with 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.


Solution

  • 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.)