Search code examples
javahttp-headershttp2

HTTP/2 Response Header in Java


Is there already a way to get the HTTP/2 response header in Java? I've tried to search in some libraries like URLConnection, Undertow or even Jetty, but without success.

P.S.: I'm using JDK 1.7 on my Java Project.

Other thing, the response header of the HTTP/2 is like this?

 GET / HTTP/1.1
 Host: server.example.com
 Connection: Upgrade, HTTP2-Settings
 Upgrade: h2c
 HTTP2-Settings: <base64url encoding of HTTP/2 SETTINGS payload>

Is there any website who use this version already?

My main goal is to know if a website use the HTTP/2 version or not, is there a way to know this without need to read the response header in a Java Project?

Thanks.


Solution

  • HTTP/2 websites typically use TLS, because browsers only support HTTP/2 over TLS.

    The method you are trying to use is the HTTP/1.1 upgrade to HTTP/2 which very few sites - if any at all - support.

    Your snippet of code represent a request, not a response. If the upgrade is successful, the HTTP/2 server sends back a 101 response in HTTP/1.1 format and the response to the GET request in HTTP/2 format. This is specified in RFC 7540, section 3.2.

    In order to achieve what you want, i.e. to know if a website supports HTTP/2, you have to try to connect using HTTP/2 + TLS. If the connection succeeds, you know HTTP/2 is supported. If it fails, it's not supported.

    For Jetty (disclaimer, I'm the HTTP/2 module maintainer), you have to use JDK 8, and the code will look like this:

    // Setup.
    HTTP2Client http2Client = new HTTP2Client();
    SslContextFactory sslContextFactory = new SslContextFactory();
    HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client), sslContextFactory);
    httpClient.start();
    
    // Does webtide.com support HTTP/2 ?
    ContentResponse response = httpClient.GET("https://webtide.com/");
    // No errors, yes it supports HTTP/2 !
    

    If you get a response without errors, you are on HTTP/2, otherwise the server does not support HTTP/2.

    Remember that for that code to work, you have to use JDK 8 and the proper ALPN boot jar in the bootclasspath, as specified here.