My new website on Artificial Intelligence and Machine Learning www.aimlfront.com

JAX-RS client API

The JAX-RS client API is a Java based API used to access Web resources. It is not restricted to resources implemented using JAX-RS. It provides a higher-level abstraction compared to a plain HTTP communication API as well as integration with the JAX-RS extension providers, in order to enable concise and efficient implementation of reusable client-side solutions that leverage existing and well established client-side implementations of HTTP-based communication.

The JAX-RS Client API encapsulates the Uniform Interface Constraint - a key constraint of the REST architectural style - and associated data elements as client-side Java artifacts and supports a pluggable architecture by defining multiple extension points.

Client API Bootstrapping and Configuration

The main entry point to the API is a ClientBuilder that is used to bootstrap Client instances - configurable, heavy-weight objects that manage the underlying communication infrastructure and serve as the root objects for accessing any Web resource. The following example illustrates the bootstrapping and configuration of a Client instance:

Client client = ClientBuilder.newClient();

client.property("propertyName", "propertyValue")
.register(MyProvider.class)
.enable(MyFeature.class);
			

Accessing Web Resources

A Web resource can be accessed using a fluent API in which method invocations are chained to configure and ultimately submit an HTTP request. The following example gets a text/plain representation of the resource identified by "http://example.org/hello":

Client client = ClientBuilder.newClient();
Response res = client.target("http://example.org/hello").request("text/plain").get();
			

Conceptually, the steps required to submit a request are the following:

  1. obtain an Client instance
  2. create a WebTarget pointing at a Web resource
  3. build a request
  4. submit a request to directly retrieve a response or get a prepared Invocation for later submission

Sample application for JAX-RS client API

This is my sample rest class

package com.javavillage.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/sample")
public class SampleRest {
	@Path("/msg/{nm}")
	@GET
	@Produces(MediaType.TEXT_HTML)
	public String getMessage(@PathParam("nm") String name)
	{
		return "<html><body>Welcome to Restful Services "+name+" </body></html>";
	}
	
	@Path("/textMessage")
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String getTextMessage()
	{
		return "This is a text message";
	}
}

web.xml changes for Rest example

<servlet>
	<servlet-name>Jersey</servlet-name>
	<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
	<init-param>
		<param-name>jersey.config.server.provider.packages</param-name>
		<param-value>com.javavillage.rest</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>Jersey</servlet-name>
	<url-pattern>/resource/*</url-pattern>
</servlet-mapping>

mvn dependencies for this project pom.xml

		
<dependency>
	<groupId>org.glassfish.jersey.containers</groupId>
	<!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" -->
	<artifactId>jersey-container-servlet</artifactId>
	<version>2.13</version>
</dependency>
<!-- Required only when you are using JAX-RS Client -->
<dependency>
	<groupId>org.glassfish.jersey.core</groupId>
	<artifactId>jersey-client</artifactId>
	<version>2.13</version>
</dependency>								

just build the project and try running with the server. Here is the output

REST result

This is my JAX-RS client sample. Create one more project with below class

	
package com.javavillage.restclient;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

public class FirstClient {
	public static void main(String[] args) {
		Client client=ClientBuilder.newClient();
		WebTarget target=
				client.target("http://localhost:8080/JaxRsMavenPrj/resource/sample/textMessage");
		String message=target.request().accept(MediaType.TEXT_PLAIN).get(String.class);
		System.out.println("Message received: "+message);
		
	}

}

mvn dependencies for this project pom.xml

 <dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.13</version>
</dependency>

Here is the output

JAX RS Client result

Here is the sample code for JSON

Client client=ClientBuilder.newClient();
HttpAuthenticationFeature authFeature=HttpAuthenticationFeature.basic("user1", "pass1");
client.register(authFeature);
		WebTarget target=
		client.target("http://localhost:8080/JsonPrj/resource/cust/all");
List<Customer> customers=
 target.request().accept(MediaType.APPLICATION_JSON).get(new GenericType<List<Customer>>(){});
for(Customer customer:customers)
{
	System.out.println(customer.getId()+"\t"+
				customer.getName()+"\t"+customer.getBalance());
}