15. JerseyのクライアントAPIを使用してRESTfulなリソースへアクセス

Jersey is the Reference Implementation of JAX-RS. The Jersey Client API is an easy-to-use and high-level Java API that can help you write clients for any HTTP-based RESTful Web service.

This section will create a client that will access the RESTful resource published at the /customers/{id} path.

  1. Right-click on the project, select “New”, “Java Class...”, give the class name as “RESTfulClient”, take all other defaults, and click on “Finish”.
  2. Add the following code to the generated class:
public static void main(String[] args) {
    String BASE_URL = "http://localhost:8080/JavaEE6SampleApp/restful/customers/";
    Client client = Client.create();
    WebResource resource = client.resource(BASE_URL + "1");
    resource.addFilter(new LoggingFilter());
    resource.get(String.class);

    resource.accept(MediaType.APPLICATION_JSON).get(String.class);
}

Notice the following points:

  • This code creates a new Jersey client runtime instance. This is an expensive object and so must be saved if no other configuration is required to access the resources.
  • A new WebResource is created per RESTful resource that is capable of building requests to send to the resource and processing responses returned from the resource. Each WebResource follows a builder pattern to specify the required MIME type in the response, application/json in this case.
  • A LoggingFilter is added to the resource to print the request and response messages.
  • The code then requests a default and JSON representation of the resource in two separate calls.

Fix the imports by taking all the defaults.

  1. Right-click on the file and select “Run File” to see the following output:

The output shows request and response messages to/from the resource. The first pair of messages is pre-fixed with “1” and shows the default XML response coming back. The second pair of messages is pre-fixed with “2” and shows the “Accept” header going from client to endpoint for content-negotiation with server. The server understands the expected format and returns a JSON response.

Project Versions

前のトピックへ

14. JAX-RSを用いてEJBをRESTfulなリソースとして公開

次のトピックへ

16. CDI修飾子を利用してBeanをインジェクト

このページ