Java HTTP client common libraries

foreword

The most commonly used library in each programming language is probably the Http request library, such as the requests package in python and the request module in nodejs.
In the Java world, a hundred flowers are blooming, and there are many mountains. Commonly used are:

  • HttpURLConnection: The class provided by the earliest JDK
  • HttpClient provided by Java 11
  • HTTPClient in the Apache HttpComponents project
  • OkHttpClient provided by Square
  • Spring's own WebClient

Apache HttpComponents

This component provides two core classes:

  • HttpCore: lower-level transmission processing class
  • HttpClient: HTTP-compliant processing class implemented based on HttpCore

Example of using JDK 11+ HTTP Client

Post synchronized json data:

public void invokePost() {
    
    
  
  try {
    
    
   String requestBody = prepareRequest();
   HttpClient client = HttpClient.newHttpClient();
   HttpRequest request = HttpRequest
     .newBuilder()
     .uri(URI.create("https://reqbin.com/echo/post/json"))
     .POST(HttpRequest.BodyPublishers.ofString(requestBody))
     .header("Accept", "application/json")
     .build();

   HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

   System.out.println(response.body());
  } catch (IOException | InterruptedException e) {
    
    
   e.printStackTrace();
  }
 }

 private String prepareRequest() throws JsonProcessingException {
    
    
  var values = new HashMap<String, String>() {
    
    
   {
    
    
    put("Id", "12345");
    put("Customer", "Roger Moose");
    put("Quantity", "3");
    put("Price","167.35");
   }
  };

  var objectMapper = new ObjectMapper();
  String requestBody = objectMapper.writeValueAsString(values);
  return requestBody;
 }

Send an asynchronous request:

public void invoke() throws URISyntaxException {
    
    
  
  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();
 }

HTTP Client Wrapper Library

cVurl

cVurl is an open-source wrapper for the Java HTTP client. It is written in Java 11 and can be used with any JDK 11.0.2 or newer.

public void cVurl() {
    
    
    CVurl cVurl = new CVurl();

    //POST
    Result result = cVurl.post("https://api.imgflip.com/caption_image")
        .queryParams(Map.of(
                "template_id", "112126428",
        "username", "test-user",
        "password", "123test321",
        "text0", "text0",
        "text1", "text1"
        ))
        .asObject(Result.class);

    System.out.println("CVurl POST: " + result);
}

It supports features such as Compression, Multipart, and Form data that Java 11 HttpClient does not have.

Avaje-HTTP

  • Fluid API for building URLs and payload
  • JSON marshaling using Avaje Jsonb/Jackson/Gson
  • Light Feign-style interfaces via annotation processing.
  • Request/Response Interception
  • Authorization via Basic Auth or OAuth Bearer Tokens
  • Async and sync API

personal suggestion

In actual projects, design an HTTP client interface that meets your own project requirements, and implement it based on JDK 11 HTTP client, independent of any of the above libraries.

reference link

  • https://github.com/corese4rch/cvurl
  • https://github.com/avaje/avaje-http/tree/master
  • https://reflectoring.io/comparison-of-java-http-clients/

Guess you like

Origin blog.csdn.net/jgku/article/details/132140905