Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Http Client API(since java 9) in Java8 project

Java 9 imports a new HTTP/2 Client API which seems good to use but is there any way to use it in Java 8?

OR

Is there any shim/polyfill(from javascript) available to make it available in Java 8?

like image 647
Ian Hu Avatar asked Jan 29 '23 13:01

Ian Hu


2 Answers

Is there any way to use it in java 8?

No, because the jdk.incubator.http module has been added since Java 9.

So it wouldn't be possible to compile it with a --release 8 option on the compiler work with Java8. You would end up getting errors as:

$ javac --release 8 .../src/com/HttpGet.java 

$ .../src/com/HttpGet.java:3: error: package jdk.incubator.http does not exist
import jdk.incubator.http.HttpClient;
                         ^

With minimal code to reproduce this as:-

import jdk.incubator.http.HttpClient;

public class HttpGet {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
        System.out.println(httpClient.version());
    }
}

Moreover, the documentation clearly reads this upfront

Incubating Feature. Will be removed in a future release.

like image 132
Naman Avatar answered Feb 02 '23 12:02

Naman


In principle, the source for it is available. You could copy it, compile it and create a jar usable with Java 8 (possibly with some changes or missing features if the code needs Java 9 anywhere), similarly to ThreeTen-Backport providing java.time for Java 6/7.

But there doesn't seem to be one available yet (after a quick search). If you decide to go in this direction, make sure to follow the relevant licenses.

like image 39
Alexey Romanov Avatar answered Feb 02 '23 10:02

Alexey Romanov