Using Java 9 HTTP Client with JUnit and Maven

Java 9 comes with built-in HTTP (2) client (incubator status):


import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.Duration;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;

public class HttpClientTest {

    private HttpClient client;

    @Before
    public void init() {
        this.client = HttpClient.newHttpClient();
    }

    @Test
    public void get() throws IOException, InterruptedException {
        URI uri = URI.create("http://airhacks.com");
        HttpRequest getRequest = HttpRequest.newBuilder(uri).
                GET().
                timeout(Duration.ofMillis(500)).
                build();
        HttpResponse<String> response = this.client.send(getRequest,
                HttpResponse.BodyHandler.asString(Charset.defaultCharset()));
        String payload = response.body();
        assertThat(payload, containsString("java"));
    }
}

The HTTP client resides in jdk.incubator.httpclient module and has to be "required". The module-info.java resides in src/main/java:

module com.airhacks.http {
    requires jdk.incubator.httpclient;
}

You will need the maven-compiler-plugin at least in the version > 3.6.1


<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
    </plugin>
</plugins>
</build>    

Now the unit tests compiles, but the execution fails with:


java.lang.NoClassDefFoundError: Ljdk/incubator/http/HttpClient;
    at java.base/java.lang.Class.getDeclaredFields0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredFields(Class.java:3024)
    at java.base/java.lang.Class.getDeclaredFields(Class.java:2205)    

Although the module is declared, it has to be still added with the following JVM argument:


<properties>
    <argLine>--add-modules jdk.incubator.httpclient</argLine>
(...)
</properties>
See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License