HTTPClient
replaces the legacy HttpUrlConnection
class present in the JDK since the early versions of Java.
Some of its features include:
- Support for HTTP/1.1, HTTP/2, and Web Socket.
- Support for synchronous and asynchronous programming models.
- Handling of request and response bodies as reactive streams.
- Support for cookies.
HttpClient
is preferred if our application is built using Java 11 and above.Apache HttpClient
Spring WebClient is an asynchronous, reactive HTTP client introduced in Spring 5 in the Spring WebFlux project to replace the older RestTemplate for making REST API calls in applications built with the Spring Boot framework. It supports synchronous, asynchronous, and streaming scenarios.
WebClient client = WebClient.create();
client
.get()
.uri(URLConstants.URL)
.header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
.retrieve()
.bodyToMono(String.class)
.subscribe(result->System.out.println(result));
WebClient client = WebClient.create();
String result = client
.post()
.uri("https://reqbin.com/echo/post/json")
.body(BodyInserters.fromValue(prepareRequest()))
.exchange()
.flatMap(response -> response.bodyToMono(String.class))
.block();
System.out.println("result::" + result);
CloseableHttpAsyncClient client =
HttpAsyncClients.createDefault();) {
client.start();
final SimpleHttpRequest request =
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost)
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_2)
.followRedirects(Redirect.NORMAL)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(URLConstants.URL))
.GET()
.header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
.timeout(Duration.ofSeconds(10))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();