4. Your First Client
The REST client calls the service from the previous page and parses
the response into the same Pet bean. With that server still running, create
src/main/java/com/example/demo/Client.java:
// Artifact: juneau-rest-client
package com.example.demo;
import org.apache.juneau.marshall.json5.*;
import org.apache.juneau.rest.client.*;
public class Client {
public static void main(String[] args) throws Exception {
try (RestClient client = RestClient.builder()
.rootUrl("http://localhost:10000")
.serializer(Json5Serializer.create().build())
.parser(Json5Parser.create().build())
.build()) {
try (var resp = client.get("/pets/{id}").pathData("id", 1).run()) {
resp.assertOk();
Pet pet = resp.body().as(Pet.class);
System.out.println(pet.id + " " + pet.name);
}
}
}
}
Run it from a second terminal in the project directory:
mvn compile exec:java -Dexec.mainClass=com.example.demo.Client
It prints 1 Fido, followed by a log line for the request.
Always close the response (it holds the connection) and close the client at shutdown; the try blocks above do both.
juneau-rest-client (org.apache.juneau.rest.client.RestClient) is the recommended REST client. It is generally
available in 10.0.0, transport-agnostic, and uses the JDK HttpClient by default. juneau-rest-client-classic
(org.apache.juneau.rest.client.classic.RestClient, Apache HttpClient 4.5) stays supported and is not deprecated; it is
the stable choice for existing users. See Choosing a REST Client.
A typed proxy instead
For services you call often, declare an interface and let Juneau implement it. See Declarative Remote-Proxy Features.
Learn more
Requests, responses, assertions, and security.
Where next?
You now have a serializer, a REST resource, and a client. The Ecosystem Overview lists everything else, and the Starter Projects show a complete deployable app.
Next: pick a guide. The Guides each do one task end to end, from a Spring Boot API to a typed client.