2018-10-19

Java 9 : HTTP/2 client

Java's HTTP API has been the most primitive. Developers often resort to using third
party libraries, such as Apache HTTP, RESTlet, Jersey, and so on. In addition to this,
Java's HTTP API predates the HTTP/1.1 specification and is synchronous and hard
to maintain. These limitations called for the need to add a new API. The new HTTP
client API provides the following:

  • A simple and concise API to deal with most HTTP requests
  • Support for HTTP/2 specification
  • Better performance
  • Better security
  • A few more enhancements


Let's see a sample code to make an HTTP GET request using the new APIs. Below is
the module definition defined within the file

//module-info.java
module newfeatures{
requires jdk.incubator.httpclient;
}

The following code uses the HTTP Client API, which is part of
module:  jdk.incubator.httpclient

import jdk.incubator.http.*;
import java.net.URI;
public class Http2Feature{
public static void main(String[] args) throws Exception{
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest
.newBuilder(new URI("http://httpbin.org/get"))
.GET()
.version(HttpClient.Version.HTTP_1_1)
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandler.asString());
System.out.println("Status code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
}
}


No comments:

Post a Comment