Now that you have developed your JAX-RS resource and deployed it to the server. JAX-RS does not provide a client API itself, but several other options exist. For example, you could develop a browser based client using something as simple as HTML forms or an AJAX client using the Dojo Toolkit. Yet another option is using the Apache HTTP client API.
The instructions below describe how to develop a client using the Apache HTTP client API. These instuctions are based on the sample created in the developing JAX-RS resources instructions. Adjust the contents below based on your resource if it is different from the one in the example.
Just as was required for developing the JAX-RS resource, a development environment is required to compile the client. Follow the same steps you used to create the server development environment with a few caveats.
Now you're ready to create the actual client code. With the HttpClient API, this is somewhat trivial. The example below shows how to create a client for an HTTP GET request. Notice that the HttpClient object instance is used to invoke different instances of request method objects. There are objects for each of the HTTP request method types.
The example client shown invokes an HTTP GET request similar to what was demonstrated using a browser in the developing resources instructions.
|
Once you are able to compile and run the client, the output should look like this:
|
Before you can create a client for a POST request, you'll need to add a resource method that support POST on your resource. If you already have one, then skip to the next step. If you are using the resource that was defined in the developing resources sample, then you'll need to add a method similar to the one below to your resource. Once you've updated the resource redeploy it using the same steps as before.
|
With the resource updated, now you'll need to add the client code to invoke the new service. Let's add it in another method so that we can keep the get and post requests separate. The code to add another name looks like this:
|
Along with the method for sending the POST request, update the main method to make the call to the POST and then call the GET to check that the name was added to the list.
|
After compiling the new code, you should see the following output when you run it.
|
By building this example, you should be able to see what is generally required to build a RESTful client for a JAX-RS resource. The HttpClient API allows for much more complexity than is show here so it can be adapted to support the more advanced scenarios that your application might require.