Restful java client with Jersey Client and Server
Restful services with Jersey as both client and Server
Create a new Maven Web project in eclipse (Refer Rest service Hello World project for the same)
Project structure
s
Step 1
Update pom.xml with below dependencies
- <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>RestWithJerseyClient</groupId>
- <artifactId>RestWithJerseyClient</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>RestWithJerseyClient 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>javax.xml</groupId>
- <artifactId>jaxb-api</artifactId>
- <version>2.1</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>1.19.3</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>RestWithJerseyClient</finalName>
- </build>
- </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>RestWithJerseyClient</groupId> <artifactId>RestWithJerseyClient</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>RestWithJerseyClient 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>javax.xml</groupId> <artifactId>jaxb-api</artifactId> <version>2.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.19.3</version> </dependency> </dependencies> <build> <finalName>RestWithJerseyClient</finalName> </build> </project>
We have added dependencies for Jersey servlet,jersey client,Jaxb 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”.
- </strong><!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>
</strong><!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
- 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;
- }
- }
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
- 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);
- }
- }
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
- 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);
- }
- }
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
- package com.kb.rest.client;
- import com.sun.jersey.api.client.Client;
- import com.sun.jersey.api.client.ClientResponse;
- import com.sun.jersey.api.client.WebResource;
- publicclass RestGetClient {
- publicstaticvoid main(String[] args) {
- try {
- Client client = Client.create();
- WebResource webResource = client
- .resource("http://localhost:8080/RestWithJerseyClient/rest/userInfo");
- ClientResponse response = webResource.accept("application/xml")
- .get(ClientResponse.class);
- if (response.getStatus() != 200) {
- thrownew RuntimeException("Request Processing Failed : HTTP error code : "
- + response.getStatus());
- }
- String output = response.getEntity(String.class);
- System.out.println("Output received from Rest service ....");
- System.out.println(output);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
package com.kb.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; publicclass RestGetClient { publicstaticvoid main(String[] args) { try { Client client = Client.create(); WebResource webResource = client .resource("http://localhost:8080/RestWithJerseyClient/rest/userInfo"); ClientResponse response = webResource.accept("application/xml") .get(ClientResponse.class); if (response.getStatus() != 200) { thrownew RuntimeException("Request Processing Failed : HTTP error code : " + response.getStatus()); } String output = response.getEntity(String.class); System.out.println("Output received from Rest service ...."); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } }
Step 7
Client to make POST call
- package com.kb.rest.client;
- import com.sun.jersey.api.client.Client;
- import com.sun.jersey.api.client.ClientResponse;
- import com.sun.jersey.api.client.WebResource;
- publicclass RestPostClient {
- publicstaticvoid main(String[] args) {
- try {
- Client client = Client.create();
- WebResource webResource = client
- .resource("http://localhost:8080/RestWithJerseyClient/rest/userInfo");
- String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
- String input = xmlHeader+"<User><id>1</id><name>Roy Thomas Fielding</name><age>51</age>
- </User>";
- ClientResponse response = webResource.type("application/xml")
- .post(ClientResponse.class, input);
- if (response.getStatus() != 201) {
- thrownew RuntimeException("Request Processing Failed : HTTP error code : "
- + response.getStatus());
- }
- System.out.println("Output received from Rest service ....");
- String output = response.getEntity(String.class);
- System.out.println(output);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
package com.kb.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; publicclass RestPostClient { publicstaticvoid main(String[] args) { try { Client client = Client.create(); WebResource webResource = client .resource("http://localhost:8080/RestWithJerseyClient/rest/userInfo"); String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; String input = xmlHeader+"<User><id>1</id><name>Roy Thomas Fielding</name><age>51</age> </User>"; ClientResponse response = webResource.type("application/xml") .post(ClientResponse.class, input); if (response.getStatus() != 201) { thrownew RuntimeException("Request Processing Failed : HTTP error code : " + response.getStatus()); } System.out.println("Output received from Rest service ...."); String output = response.getEntity(String.class); System.out.println(output); } catch (Exception e) { e.printStackTrace(); } } }
Step 8
Build the war file and deploy in Tomcat
Step 9
Check the output
Run RestGetClient class
Output appears as below
Now run RestPostClient class
Output appears as below