Java JEE7 JAX-RS 2.0 Client Example

JEE6 JAX-RS 1.0 only include API for creating RESTful server application but no API for RESTFul client to consume the resources. Jersey, RESTEasy provide different API and make the client code vendor dependent. Now JEE7 JAX-RS 2.0 include Client API, which make the API vendor independent. In this blog, I will write the example of using JAX-RS 2.0.


I use maven to manage dependencies, the following pom.xml show the dependencies that I used:


The JAX-RS 2.0 implementation I use is Jersey bundled with Glassfish 4.0. However, since it is vendor independent, so whether you use JBoss, or Glassfish is the same.

Create Client to Consume Github V3 API

Now is tme to create Github client using JAX-RS 2.0. To create a instance of Client, use ClientBuilder.newClient() factory method to obtaint one.

  Client client = ClientBuilder.newClient();

A Web resource can be accessed using a fluent API in which method invocations are chained to build and ultimately submit an HTTP request. The following example gets a application/json representation of the resource identified by

  WebTarget userTarget ="{username}");
      .resolveTemplate("username", "octocat")

Note that the {username} is the template to access RESTFul API with dynamic value, in this above example, the placeholder is replaced with octocat. This is usefull to access different resources on the server.

The complete code to access user and repositories:

public class GithubClient {
    private Client client;
    private WebTarget userTarget;
    private WebTarget userRepoTarget;

    public GithubClient() {
        client = ClientBuilder.newClient();
        userTarget ="{username}");
        userRepoTarget ="{username}/repos");
    public String findUserByUsername(String username) {
        Response res = userTarget
                .resolveTemplate("username", username)
        return res.readEntity(String.class);
    public String findRepositoriesByUser(String username) {
        Response res = userRepoTarget
                .resolveTemplate("username", username)
        return res.readEntity(String.class);

After created client to consume REST resource, now create a servlet to call the client:

@WebServlet(value = "/user")
public class ClientExampleServlet extends HttpServlet {
    GithubClient client;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Then acces to browser http://localhost:8080/CONTEXT/client?username=octocat will show the following output:

   "name":"The Octocat",
   "location":"San Francisco",


With JAX-RS 2.0, now RESTFul client API is first class citizen. Vendor locking is no more and developers only need create one client using standard API.

Filed under java


Find Me