Java Reference
In-Depth Information
Client API
Historically, it has involved many lines of code to invoke REST services. That is because in order to access a REST
service, clients using HttpUrlConnection had to be created. In the JAX-RS 2.0 release, a client API has been included,
allowing developers to follow a standard API for developing clients.
To use the client API, obtain an instance of by calling the
ClientBuilder newClient method. Once a Client instance is obtained, it can be configured by setting properties or
registering Provider and/or Feature classes. Properties are simply name-value pairs that can be passed to the client
via the setProperty method. Feature s are Provider s that implement the Feature interface. A Feature can be used
for grouping related properties and Provider s into a single unit, making configuration even easier.
Let's take a look at a simple client that will call upon a target URI for the simplerest service that was created in
one of this chapter's earlier examples. In the following example, a Client instance is obtained, and then a URI target is
set. The client goes on to request a response of type application/xml and then makes the call to get the request.
public class RestClientJava {
public static void main(String[] args){
// Obtain an instance of the client
Client client = ClientBuilder.newClient();
WebTarget webTarget =" http://localhost:8080/IntroToJavaEE7/rest/simplerest " );
Response res = webTarget.request("text/plain").get();
As a result of running this client class, the output of the web service call will be written to the server log. Although
this client simply prints the result, a real client could be created using the same technique, and then it could process
the data into a more useful format. If one wished to create a web client, rather than a standard Java client, the same
JAX-RS client API can be used within a web application. For instance, the following JSF managed bean can be used to
implement the same tests as RestClientJava that was demonstrated above.
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
public class RestClientOne {
private String clientOutput;
// May be able to do @Inject before final release
public void testServiceOne(){
// Obtain an instance of the client
Client client =;
Search WWH ::

Custom Search