I just found that org.jboss.resteasy.client.ClientRequest
is deprecated, invalidating everything I could find on Google about how to use the RESTEasy
c
If we assume there is a JSON API at http://example.org/pizza/{id}.json
, (where 'id' is a pizza ID) which returns results such as
{
"name": "Hawaiian",
"toppings": ["tomato", "ham", "cheese", "pineapple"]
}
Building on the Invocation.Builder Javadocs, we can do something like this,
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import org.glassfish.jersey.jackson.JacksonFeature;
public class PizzaClient {
private Client client;
public PizzaClient() {
client = ClientBuilder.newClient();
// enable POJO mapping using Jackson - see
// https://jersey.java.net/documentation/latest/user-guide.html#json.jackson
client.register(JacksonFeature.class);
}
/** POJO which maps to JSON results using Jackson */
public static class Pizza {
private String name;
private String[] toppings;
public String getName() { return name; }
public String[] getToppings() { return toppings ; }
}
public Pizza getPizzaById(String id) {
String uri = String.format("http://example.org/pizza/%s.json", id)
Invocation.Builder bldr = client.target(uri).request("application/json");
return bldr.get(Pizza.class);
}
public static void main(String[] args) {
PizzaClient pc = new PizzaClient();
Pizza pizza = pc.getPizzaById("1");
System.out.println(pizza.getName() + ":");
for (String topping : pizza.getToppings()) {
System.out.println("\t" + topping);
}
}
}
(this is also assisted by this post although that uses the deprecated API).
Note also that you may need to register a special handler if you want to use Jackson to read POJOs (or, I think, using JAXB) as documented here
Update You actually only need the following Maven dependencies:
org.glassfish.jersey.core
jersey-client
2.3.1
org.glassfish.jersey.media
jersey-media-json-jackson
2.3.1
(In which case you're not using RestEasy at all -- the javax.ws.rs
JAXRS implementation comes from Jersey)
OR you can stick with JBoss:
org.jboss.resteasy
resteasy-jackson2-provider
3.0.4.Final
org.jboss.resteasy
resteasy-client
3.0.4.Final
In which case you can just remove the JacksonFeature line in the above code, and the code uses the more liberal Apache licence.