This post looks at how to write a service client using RESTEasy framework, which is an excellent framework for developing RESTful services, and has gained a lot of popularity in the Mobile application development world.
Also Refer to,
RESTful with RESTEasy - Part 1/4 (Creating a POST and GET RESTful Service)
You can find the sample code here.
Prerequisite:JDK >= 1.5.x
Maven >= 2.2.x
Step 1: Maven Dependencies (pom.xml)
Update your client project's pom.xml by adding the following RESTEasy dependency.
Step 1: Maven Dependencies (pom.xml)
Update your client project's pom.xml by adding the following RESTEasy dependency.
<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">
. . .
<dependencies>
. . .
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>${resteasy.version}</version>
</dependency>
. . .
</dependencies>
. . .
</project>
Step 2: How to create a requests
private static final String SERVICE_URL = "http://localhost:8080/greetingspring";
private static final String SERVICE_URL_ADD = "/add";
private static final String SERVICE_URL_UPDATED = "/update";
private static final String SERVICE_URL_GET = "/get/{id}";
private static final String SERVICE_URL_GET_ALL = "/getAll";
. . .
private static ClientRequest createRequest(String uri) {
ClientRequest request = new ClientRequest(SERVICE_URL + uri);
request.accept("application/json");
return request;
}
. . .
ClientRequest request = createRequest(SERVICE_URL_ADD)
ClientRequest request = createRequest(SERVICE_URL_GET)
ClientRequest request = createRequest(SERVICE_URL_UPDATE)
ClientRequest request = createRequest(SERVICE_URL_GET_ALL)
Creating a POST request
private static Long addUser(User newUser) throws Exception {
String requestJson = "{\"user\":" + JSON_CONVERTER.toJson(newUser) + "}";
displayRequest(requestJson);
ClientRequest request = createRequest(SERVICE_URL_ADD).body(CONTENT_TYPE, requestJson);
ClientResponse<String> response = request.post(String.class);
displayResponse(response, HTTP_CODE_CREATED);
return Long.parseLong(response.getEntity().toString());
}
Creating a GET request
private static User getUser(Long userId) throws Exception {
ClientRequest request = createRequest(SERVICE_URL_GET.replace("{id}", userId.toString()));
ClientResponse<String> response = request.get(String.class);
displayResponse(response, HTTP_CODE_OK);
String responseJson = response.getEntity().toString();
responseJson = responseJson.replace("{\"user\":", "").replace("}}", "}");
return JSON_CONVERTER.fromJson(responseJson, User.class);
}
Complete Code for the Client
package org.fazlan.resteasy.spring.client;
import com.google.gson.Gson;
import org.fazlan.resteasy.spring.entity.User;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class RestClient {
private static final String SERVICE_URL = "http://localhost:8080/greetingspring";
private static final String SERVICE_URL_ADD = "/add";
private static final String SERVICE_URL_UPDATED = "/update";
private static final String SERVICE_URL_GET = "/get/{id}";
private static final String SERVICE_URL_GET_ALL = "/getAll";
private static final String CONTENT_TYPE = "application/json";
private static final Gson JSON_CONVERTER = new Gson();
private static final int HTTP_CODE_OK = 200;
private static final int HTTP_CODE_CREATED = 201;
public static void main(String[] args) throws Exception {
User newUser = new User("Firstname", "Lastname");
Long userId = addUser(newUser);
User user = getUser(userId);
displayUser(user);
user.setFirstName("Updated " + user.getFirstName());
userId = updateUser(user);
user = getUser(userId);
displayUser(user);
addUser( new User("AnotherFirstName", "AnotherLastName"));
getAllUsers();
}
private static Long addUser(User newUser) throws Exception {
String requestJson = "{\"user\":" + JSON_CONVERTER.toJson(newUser) + "}";
displayRequest(requestJson);
ClientRequest request = createRequest(SERVICE_URL_ADD).body(CONTENT_TYPE, requestJson);
ClientResponse<String> response = request.post(String.class);
displayResponse(response, HTTP_CODE_CREATED);
return Long.parseLong(response.getEntity().toString());
}
private static Long updateUser(User user) throws Exception {
String requestJson = "{\"user\":" + JSON_CONVERTER.toJson(user) + "}";
displayRequest(requestJson);
ClientRequest request = createRequest(SERVICE_URL_UPDATED).body(CONTENT_TYPE, requestJson);
ClientResponse<String> response = request.post(String.class);
displayResponse(response, HTTP_CODE_OK);
return Long.parseLong(response.getEntity().toString());
}
private static User getUser(Long userId) throws Exception {
ClientRequest request = createRequest(SERVICE_URL_GET.replace("{id}", userId.toString()));
ClientResponse<String> response = request.get(String.class);
displayResponse(response, HTTP_CODE_OK);
String responseJson = response.getEntity().toString();
responseJson = responseJson.replace("{\"user\":", "").replace("}}", "}");
return JSON_CONVERTER.fromJson(responseJson, User.class);
}
private static void getAllUsers() throws Exception {
ClientRequest request = createRequest(SERVICE_URL_GET_ALL);
ClientResponse<String> response = request.get(String.class);
displayResponse(response, HTTP_CODE_OK);
}
private static ClientRequest createRequest(String uri) {
ClientRequest request = new ClientRequest(SERVICE_URL + uri);
request.accept("application/json");
return request;
}
private static void displayUser(User user) {
System.out.println(user);
}
private static void displayRequest(String request) {
System.out.println(request);
}
private static void displayResponse(ClientResponse<String> response, int expectedResponseCode) throws IOException {
if (response.getStatus() != expectedResponseCode) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(response.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
}
}
Summary:
This tutorial looked at how we can consume RESTful Web Service using RESTEasy.
You can find the sample code here.
No comments:
Post a Comment