Wednesday, May 25, 2022

Http Client: RestTemplate, Java11-HttpClient, Apache-HttpClient, WebClient

 HTTPClient replaces the legacy HttpUrlConnection class present in the JDK since the early versions of Java.

Some of its features include:

  1. Support for HTTP/1.1, HTTP/2, and Web Socket.
  2. Support for synchronous and asynchronous programming models.
  3. Handling of request and response bodies as reactive streams.
  4. Support for cookies.
Use of HttpClient is preferred if our application is built using Java 11 and above.

sendAsync VS send


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.


If you call Block- then it became synchronous. 

Spring WebClient is the preferred choice for Spring Boot applications more importantly if we are using reactive APIs.

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();

No comments: