Un client REST est un composant logiciel qui interagit avec des APIs RESTful. En Java, Jakarta RESTful Web Services (anciennement JAX-RS) fournit une API fluide pour construire des requêtes REST de manière élégante.
Types de Clients REST
Il existe plusieurs approches pour implémenter un client REST en Java, chacune avec ses avantages et cas d’usage spécifiques :
Client HTTP natif : Utilise l’API HTTP native de Java, idéal pour les cas simples
Client Jakarta REST : Offre une API moderne et fluide, recommandé pour les applications enterprise
Client REST asynchrone : Permet des opérations non bloquantes, parfait pour la haute performance
Client Quarkus : Simplifie le développement de microservices avec une approche déclarative
Tableau comparatif
Client HTTP natif
// filepath: /home/jovyan/work/local/02_java_rest_L_client.qmdtry{// Configuration de la connexionURL url =newURL("http://localhost:9998/mylibrary");HttpURLConnection conn =(HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept","application/json");// Vérification du code de réponseint responseCode = conn.getResponseCode();if(responseCode ==HttpURLConnection.HTTP_OK){// Lecture de la réponsetry(BufferedReader br =newBufferedReader(newInputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))){StringBuilder response =newStringBuilder();String line;while((line = br.readLine())!=null){ response.append(line);}System.out.println("Response: "+ response.toString());}}else{System.err.println("Error: "+ responseCode);}}catch(IOException e){ e.printStackTrace();}finally{if(conn !=null){ conn.disconnect();}}
Client Jakarta REST
Caractéristiques principales :
API fluide et moderne
Support natif JSON/XML
Gestion automatique des ressources
Extensible via filtres et intercepteurs
Support de la sérialisation JSON et XML :
Jackson, MOXy, Jettison, etc.
JAXB pour XML https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest31x/client.html
Classes fondamentales
// 1. Client - Point d'entrée principalClient client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();// 2. WebTarget - Représente une ressource RESTWebTarget target = client.target("http://api.example.com").path("resources").path("{id}");// 3. Response - Contient la réponse HTTPResponse response = target.request(MediaType.APPLICATION_JSON).get();
Hiérarchie des classes principales
ClientBuilder
Factory pour créer des instances Client
Configuration du client (timeout, features, providers)
CompilationException:
| try (Client client = ClientBuilder.newBuilder()
cannot find symbol
symbol: class Client
| .register(JacksonFeature.class)
cannot find symbol
symbol: class JacksonFeature
| try (Client client = ClientBuilder.newBuilder()
cannot find symbol
symbol: variable ClientBuilder
| WebTarget baseTarget = client.target(baseUrl);
cannot find symbol
symbol: class WebTarget
| .request(MediaType.APPLICATION_JSON)
cannot find symbol
symbol: variable MediaType
| .put(Entity.entity("", MediaType.TEXT_PLAIN), String.class);
cannot find symbol
symbol: variable MediaType
| .put(Entity.entity("", MediaType.TEXT_PLAIN), String.class);
cannot find symbol
symbol: variable Entity
| } catch (WebApplicationException e) {
cannot find symbol
symbol: class WebApplicationException
| WebTarget authorTarget = baseTarget.path("authors/{id}");
cannot find symbol
symbol: class WebTarget
| try (Response response = authorTarget
cannot find symbol
symbol: class Response
| .request(MediaType.APPLICATION_JSON)
cannot find symbol
symbol: variable MediaType
| if (response.getStatus() == Response.Status.OK.getStatusCode()) {
package Response.Status does not exist
| Author author = response.readEntity(Author.class);
cannot find symbol
symbol: class Author
| Author author = response.readEntity(Author.class);
cannot find symbol
symbol: class Author
| } catch (ProcessingException e) {
cannot find symbol
symbol: class ProcessingException
POST avec entité
Book newBook =newBook("Java REST","John Doe");Response response = target.request(MediaType.APPLICATION_JSON).post(Entity.entity(newBook, MediaType.APPLICATION_JSON));// Vérification de la créationif(response.getStatus()==Response.Status.CREATED.getStatusCode()){URI location = response.getLocation();System.out.println("Ressource créée à: "+ location);}
Un exemple de client REST
La classe fr.univtln.bruno.samples.jaxrs.client.BiblioClient présente un client qui utilise l’API fluent cliente pour construire des requêtes REST en Java.
Error: failed to read file /home/jovyan/work/src/github/ebpro/sample-jaxrs/src/main/java/fr/univtln/bruno/samples/jaxrs/client/BiblioClient.java: /home/jovyan/work/src/github/ebpro/sample-jaxrs/src/main/java/fr/univtln/bruno/samples/jaxrs/client/BiblioClient.java
zsh:cd:1: no such file or directory: /home/jovyan/work/src/github/ebpro/sample-jaxrs
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.6.4:java (default-cli): Goal requires a project to execute but there is no POM in this directory (/workdir). Please verify you invoked Maven from the correct directory. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MissingProjectException
Client REST asynchrone
La programmation réactive avec les clients REST permet de gérer efficacement les opérations d’E/S non bloquantes, améliorant ainsi les performances des applications.
Principes clés
Non-blocking I/O : Les opérations d’E/S n’immobilisent pas les threads
Back-pressure : Contrôle du flux de données entre producteur et consommateur
Scalabilité : Meilleure utilisation des ressources système
Résilience : Gestion améliorée des erreurs et des timeouts
Quarkus REST Client
Quarkus fournit un client REST déclaratif qui simplifie l’intégration avec les APIs REST.