Restful java client with RestEasy


Restful services with Jersey and RestEasy client

Create a new Maven Web project in eclipse (Refer Rest service Hello World project for the same)

Project structure


RestWithRestEasy_project_structure

Step 1

Update pom.xml with below dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  4.         http://maven.apache.org/maven-v4_0_0.xsd">
  5.  
  6.          <modelVersion>4.0.0</modelVersion>
  7.          <groupId>RestWithRestEasy</groupId>
  8.          <artifactId>RestWithRestEasy</artifactId>
  9.          <packaging>war</packaging>
  10.          <version>0.0.1-SNAPSHOT</version>
  11.          <name>RestWithRestEasy MavenWebapp</name>
  12.          <url>http://maven.apache.org</url>
  13.  
  14.     <dependencies>
  15.  
  16.         <dependency>
  17.               <groupId>junit</groupId>
  18.               <artifactId>junit</artifactId>
  19.               <version>3.8.1</version>
  20.               <scope>test</scope>
  21.         </dependency>
  22.  
  23.        <dependency>
  24.               <groupId>junit</groupId>
  25.               <artifactId>junit</artifactId>
  26.               <version>3.8.1</version>
  27.               <scope>test</scope>
  28.        </dependency>
  29.  
  30.        <dependency>
  31.               <groupId>org.glassfish.jersey.containers</groupId>
  32.               <artifactId>jersey-container-servlet</artifactId>
  33.               <version>2.24</version>
  34.        </dependency>
  35.  
  36.        <dependency>
  37.               <groupId>org.jboss.resteasy</groupId>
  38.               <artifactId>resteasy-jaxb-provider</artifactId>
  39.               <version>3.0.2.Final</version>
  40.        </dependency>
  41.  
  42.                      <!-- core library -->
  43.        <dependency>
  44.               <groupId>org.jboss.resteasy</groupId>
  45.               <artifactId>resteasy-jaxrs</artifactId>
  46.               <version>3.0.2.Final</version>
  47.        </dependency>
  48.  
  49.        <dependency>
  50.               <groupId>org.jboss.resteasy</groupId>
  51.               <artifactId>jaxrs-api</artifactId>
  52.               <version>3.0.2.Final</version>
  53.        </dependency>
  54.  
  55.        <dependency>
  56.               <groupId>org.jboss.resteasy</groupId>
  57.               <artifactId>resteasy-client</artifactId>
  58.               <version>3.0.2.Final</version>
  59.         </dependency>
  60.  
  61. </dependencies>
  62.  
  63. <build>
  64. <finalName>RestWithRestEasy</finalName>
  65. </build>
  66.  
  67. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/maven-v4_0_0.xsd">

         <modelVersion>4.0.0</modelVersion>
         <groupId>RestWithRestEasy</groupId>
         <artifactId>RestWithRestEasy</artifactId>
         <packaging>war</packaging>
         <version>0.0.1-SNAPSHOT</version>
         <name>RestWithRestEasy MavenWebapp</name>
         <url>http://maven.apache.org</url>

    <dependencies>

        <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>3.8.1</version>
              <scope>test</scope>
        </dependency>

       <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>3.8.1</version>
              <scope>test</scope>
       </dependency>

       <dependency>
              <groupId>org.glassfish.jersey.containers</groupId>
              <artifactId>jersey-container-servlet</artifactId>
              <version>2.24</version>
       </dependency>

       <dependency>
              <groupId>org.jboss.resteasy</groupId>
              <artifactId>resteasy-jaxb-provider</artifactId>
              <version>3.0.2.Final</version>
       </dependency>

                     <!-- core library -->
       <dependency>
              <groupId>org.jboss.resteasy</groupId>
              <artifactId>resteasy-jaxrs</artifactId>
              <version>3.0.2.Final</version>
       </dependency>

       <dependency>
              <groupId>org.jboss.resteasy</groupId>
              <artifactId>jaxrs-api</artifactId>
              <version>3.0.2.Final</version>
       </dependency>

       <dependency>
              <groupId>org.jboss.resteasy</groupId>
              <artifactId>resteasy-client</artifactId>
              <version>3.0.2.Final</version>
        </dependency>

</dependencies>

<build>
<finalName>RestWithRestEasy</finalName>
</build>

</project>

We have added dependencies for Jersey servlet,Jaxb,Rest Easy and Junit in the above pom file.

Step 2

Update web.xml file with Jersey servlet container

we have defined a special servlet called “jersey-serlvet” in web.xml and mapped it by the URL pattern /rest/*

So just like any other servlet in web application,any request matching with the given pattern i.e /rest/* will be redirected to “Jersey servelt”.
Create web.xml as below

  1. <!DOCTYPEweb-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  2.                        "http://java.sun.com/dtd/web-app_2_3.dtd">
  3.  
  4. <web-app>
  5.       <display-name>Archetype Created Web Application</display-name>
  6.         <servlet>
  7.         <servlet-name>jersey-serlvet</servlet-name>
  8.         <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
  9.         <init-param>
  10.             <param-name>jersey.config.server.provider.packages</param-name>
  11.             <param-value>com.kb.rest.resource</param-value>
  12.         </init-param>
  13.         <load-on-startup>1</load-on-startup>
  14.     </servlet>
  15.  
  16.     <servlet-mapping>
  17.         <servlet-name>jersey-serlvet</servlet-name>
  18.         <url-pattern>/rest/*</url-pattern>
  19.     </servlet-mapping>
  20. </web-app>
<!DOCTYPEweb-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                       "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
      <display-name>Archetype Created Web Application</display-name>
        <servlet>
		<servlet-name>jersey-serlvet</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.kb.rest.resource</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
</web-app>

We have also provided the package of java classes(to be qualified as Rest services) under init-param tag.

This package will be considered by Jersey servlet container to identify the actual service when the request comes in.

Step 3

Create a Resource class as below

  1. package com.kb.rest.resource;
  2.  
  3. import java.util.List;
  4.  
  5. import javax.ws.rs.Consumes;
  6. import javax.ws.rs.GET;
  7. import javax.ws.rs.POST;
  8. import javax.ws.rs.Path;
  9. import javax.ws.rs.Produces;
  10. import javax.ws.rs.core.MediaType;
  11. import javax.ws.rs.core.Response;
  12.  
  13. import com.kb.model.User;
  14. import com.kb.service.UserService;
  15.  
  16. @Path("/userInfo")
  17. public class UserResource {
  18.     UserService userService = new UserService();
  19.  
  20.     @POST
  21.     @Consumes(MediaType.APPLICATION_XML)
  22.     public Response createUser(User user) {
  23.         userService.createUser(user);
  24.         String result = "User created with " + "ID: "+user.getId();
  25.         return Response.status(201).entity(result).build();
  26.  
  27.     }
  28.  
  29.     @GET
  30.     @Produces(MediaType.APPLICATION_XML)
  31.     public List<User> getAllUsers() {
  32.         List<User> userList = userService.getAllUsers();
  33.         return userList;
  34.     }
  35. }
package com.kb.rest.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.kb.model.User;
import com.kb.service.UserService;

@Path("/userInfo")
public class UserResource {
	UserService userService = new UserService();

	@POST
	@Consumes(MediaType.APPLICATION_XML)
	public Response createUser(User user) {
		userService.createUser(user);
		String result = "User created with " + "ID: "+user.getId();
		return Response.status(201).entity(result).build();

	}

	@GET
	@Produces(MediaType.APPLICATION_XML)
	public List<User> getAllUsers() {
		List<User> userList = userService.getAllUsers();
		return userList;
	}
}


@Path(“/userInfo”)


This annotation helps to map the request URL to appropriate Rest service.

So any request with /userInfo (relative to the base URI) will be mapped to UserResource.

This annotation should be used either at the class level or at the method level.

@GET


This annotation specifies that only GET requests will be accepted by this method.

This annotation will be used at the method level.


@POST


This annotation specifies that only POST requests will be accepted by this method.

This annotation will be used at the method level.


@Consumes(MediaType.APPLICATION_XML)


This annotation is used to specify the representation of a data (MIME type) that the service can accept from the client.

This annotation can be used either at the class level or at the method level.

If this annotation is applied at the class level,all the methods in the class will accept the same MIME type data from client by default.

However we can override this at the method level with different MIME type.

We can also specify multiple MIME types as below@Consumes({“application/xml”, “application/json”})

Note:

We should Use application/xml for the xml to be processed by programs and we should use text/xml if we are using xml for human reading purposes.


@Produces(MediaType.APPLICATION_XML)


This annotation is used to specify the representation of a data (MIME type) that the service can produce and send it to client.

This annotation can be used either at the class level or at the method level.

If this annotation is applied at the class level,all the methods in the class can produce the same MIME type data by default.

However we can override this at the method level with different MIME type.

We can also specify multiple MIME types as below@Produces({“application/xml”, “application/json”})

Step 4

Create the business Service class as below

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.dao.UserDAO;
  6. import com.kb.model.User;
  7.  
  8. public class UserService {
  9.     UserDAO userDao = new UserDAO();
  10.  
  11.     public List<User> getAllUsers() {
  12.         List<User> userList = userDao.getAllUsers();
  13.         return userList;
  14.     }
  15.  
  16.     public void createUser(User user) {
  17.         userDao.createUser(user);
  18.     }
  19.  
  20. }
package com.kb.service;

import java.util.List;

import com.kb.dao.UserDAO;
import com.kb.model.User;

public class UserService {
	UserDAO userDao = new UserDAO();

	public List<User> getAllUsers() {
		List<User> userList = userDao.getAllUsers();
		return userList;
	}

	public void createUser(User user) {
		userDao.createUser(user);
	}

}


Step 5

Create a DAO class as below

  1. package com.kb.dao;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6.  
  7. import com.kb.model.User;
  8.  
  9. //Just to avoid DB calls in this example, Assume below data is interacting with DB
  10. public class UserDAO {
  11.     static HashMap<String, User> usersMap = new HashMap<String, User>();
  12.  
  13.     public UserDAO() {
  14.             User user1 = new User();
  15.             user1.setId("1");
  16.             user1.setAge(20);
  17.             user1.setName("raj");
  18.            
  19.             User user2 = new User();
  20.             user2.setId("2");
  21.             user2.setAge(21);
  22.             user2.setName("ram");
  23.            
  24.             usersMap.put("1", user1);
  25.             usersMap.put("2", user2);
  26.     }
  27.  
  28.     public List<User> getAllUsers() {
  29.  
  30.         List<User> userList = new ArrayList<User>(usersMap.values());
  31.         return userList;
  32.     }
  33.  
  34.     public void createUser(User user) {
  35.         usersMap.put(user.getId(), user);
  36.     }
  37.  
  38. }
package com.kb.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.kb.model.User;

//Just to avoid DB calls in this example, Assume below data is interacting with DB
public class UserDAO {
	static HashMap<String, User> usersMap = new HashMap<String, User>();

	public UserDAO() {
			User user1 = new User();
			user1.setId("1");
			user1.setAge(20);
			user1.setName("raj");
			
			User user2 = new User();
			user2.setId("2");
			user2.setAge(21);
			user2.setName("ram");
			
			usersMap.put("1", user1);
			usersMap.put("2", user2);
	}

	public List<User> getAllUsers() {

		List<User> userList = new ArrayList<User>(usersMap.values());
		return userList;
	}

	public void createUser(User user) {
		usersMap.put(user.getId(), user);
	}

}


Create the classes for java client

Step 6

Client to make GET call

  1. package com.kb.rest.client;
  2.  
  3. import javax.ws.rs.core.Response;
  4.  
  5. import org.jboss.resteasy.client.jaxrs.ResteasyClient;
  6. import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
  7. import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
  8.  
  9. public class RestGetClient {
  10.     public static void main(String[] args) {
  11.             ResteasyClient client = new ResteasyClientBuilder().build();
  12.             ResteasyWebTarget target = client.target("http://localhost:8080/RestWithRestEasy/rest/userInfo");
  13.             Response response = target.request().get();
  14.            
  15.                 //Read output in string format
  16.             String value = response.readEntity(String.class);
  17.             System.out.println(value);
  18.             response.close();  
  19.             if (response.getStatus() != 200) {
  20.                 throw new RuntimeException("Request Processing Failed : HTTP error code : "
  21.                    + response.getStatus());
  22.             }
  23.  
  24.       }
  25. }
package com.kb.rest.client;

import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

public class RestGetClient {
	public static void main(String[] args) {
			ResteasyClient client = new ResteasyClientBuilder().build();
	        ResteasyWebTarget target = client.target("http://localhost:8080/RestWithRestEasy/rest/userInfo");
	        Response response = target.request().get();
	       
                //Read output in string format
	        String value = response.readEntity(String.class);
	        System.out.println(value);
	        response.close();  
			if (response.getStatus() != 200) {
				throw new RuntimeException("Request Processing Failed : HTTP error code : "
				   + response.getStatus());
			}

      }
}
Step 7

Client to make POST call

  1. package com.kb.rest.client;
  2.  
  3. import javax.ws.rs.client.Entity;
  4. import javax.ws.rs.core.Response;
  5.  
  6. import org.apache.http.HttpStatus;
  7. import org.jboss.resteasy.client.jaxrs.ResteasyClient;
  8. import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
  9. import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
  10.  
  11. import com.kb.model.User;
  12.  
  13. public class RestPostClient {
  14.     public static void main(String[] args) {
  15.         ResteasyClient client = new ResteasyClientBuilder().build();
  16.         User user = new User();
  17.         user.setId("1");
  18.         user.setName("Roy Thomas Fielding");
  19.         user.setAge(51);
  20.         ResteasyWebTarget target = client.target("http://localhost:8080/RestWithRestEasy/rest/userInfo");
  21.         Response response = target.request().post(Entity.entity(user, "application/xml"));
  22.         if (response.getStatus() != HttpStatus.SC_CREATED) {
  23.             throw new RuntimeException("Request Processing Failed : HTTP error code : " +  
  24.                                                                                              response.getStatus());
  25.         }
  26.         // Reading output in string format
  27.          String value = response.readEntity(String.class);
  28.             System.out.println(value);
  29.         System.out.println(response.getStatus());
  30.         response.close();
  31.     }
  32.  
  33. }
package com.kb.rest.client;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.apache.http.HttpStatus;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.kb.model.User;

public class RestPostClient {
	public static void main(String[] args) {
		ResteasyClient client = new ResteasyClientBuilder().build();
		User user = new User();
		user.setId("1");
		user.setName("Roy Thomas Fielding");
		user.setAge(51);
		ResteasyWebTarget target = client.target("http://localhost:8080/RestWithRestEasy/rest/userInfo");
		Response response = target.request().post(Entity.entity(user, "application/xml"));
		if (response.getStatus() != HttpStatus.SC_CREATED) {
			throw new RuntimeException("Request Processing Failed : HTTP error code : " +  
                                                                                             response.getStatus());
		}
		// Reading output in string format
		 String value = response.readEntity(String.class);
	        System.out.println(value);
		System.out.println(response.getStatus());
		response.close();
	}

}
Step 8

Build the war file and deploy in Tomcat

Step 9

Check the output

Run RestGetClient class

Output appears as below

RestWithRestEasy_get_output

Now run RestPostClient class

Output appears as below

RestWithResteasy_post_output

Download this project RestWithRestEasy.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on