Créer Java RESTful Client avec Jersey Client
1. Mục tiêu của tài liệu
Dans ce document, je vais vous donner des instructions de créer Java RESTful Client en utilisant Jersey Client API pour appeler RESTful web service.
Les exemples présents dans ce document se refèrent RESTful Web service dans la leçon précédente, vous pouvez voir ici:
2. Tạo Maven Project
Assurez- vous que votre projet utilise Java >=6, parce que dans ce projet, il utilisera des bibliothèques JAXB, qui étaient construit dans Jdk6 ou plus récent.
Project Properties:
La déclaration de la bibliothèque Jersey Client:
pom.xml
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o7planning</groupId>
<artifactId>JerseyRESTClient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>JerseyRESTClient</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-json -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.19.2</version>
</dependency>
</dependencies>
</project>
3. Model Classes
Par défaut, Jersey API est le défaut JAXB là XML-Binding qui a utilisé à convertir un objet Java en XML et vice versa, vous devez attacher Annotation de JAXB sur des classes model afin d'annoter et d'expliquer la manière de convertissement pour JAXB.
Et MOXy est le défaut JSON-Binding pour que Jersey convertisse des objets JSON en Java et vice verssa, vous ne devez pas attacher Annotation quiconque sur des classes model.
Et MOXy est le défaut JSON-Binding pour que Jersey convertisse des objets JSON en Java et vice verssa, vous ne devez pas attacher Annotation quiconque sur des classes model.
Employee.java
package org.o7planning.jerseyrestclient.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee {
private String empNo;
private String empName;
private String position;
// This default constructor is required if there are other constructors.
public Employee() {
}
public Employee(String empNo, String empName, String position) {
this.empNo = empNo;
this.empName = empName;
this.position = position;
}
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
4. Get JSON thành String
L'exemple suivant crée une classe, appel à RESTful Web Serivce pour récupérer les données en tant que JSON, le résultat renvoyé est une String.
GetJsonAsString.java
package org.o7planning.jerseyrestclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class GetJsonAsString {
public static void main(String[] args) {
// Create Client
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees/E01");
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
}
}
5. Get JSON thành Object
L'exemple ci-dessous, Jersey Client convertit des données JSON en des objets Java.
GetJsonAsObject.java
package org.o7planning.jerseyrestclient;
import javax.ws.rs.core.MediaType;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class GetJsonAsObject {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
// Create Client based on Config
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees/E01");
Builder builder = webResource.accept(MediaType.APPLICATION_JSON) //
.header("content-type", MediaType.APPLICATION_JSON);
ClientResponse response = builder.get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
System.out.println("Output from Server .... \n");
Employee employee = (Employee) response.getEntity(Employee.class);
System.out.println("Emp No .... " + employee.getEmpNo());
System.out.println("Emp Name .... " + employee.getEmpName());
System.out.println("Position .... " + employee.getPosition());
}
}
6. Get JSON thành List
Jersey peut convertir une JSON en une List.
L'exemple RESTful Web Service renvoie une List des objets.
@Path("/employees")
public class EmployeeService {
// URI:
// /contextPath/servletPath/employees
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> getEmployees() {
List<Employee> listOfCountries = EmployeeDAO.getAllEmployees();
return listOfCountries;
}
}
L'exemple Client:
GetJsonAsList.java
package org.o7planning.jerseyrestclient;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class GetJsonAsList {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
// Create Client based on Config
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
Builder builder = webResource.accept(MediaType.APPLICATION_JSON) //
.header("content-type", MediaType.APPLICATION_JSON);
ClientResponse response = builder.get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
GenericType<List<Employee>> generic = new GenericType<List<Employee>>() {
// No thing
};
List<Employee> list = response.getEntity(generic);
System.out.println("Output from Server .... \n");
for (Employee emp : list) {
System.out.println(" --- ");
System.out.println("Emp No .... " + emp.getEmpNo());
System.out.println("Emp Name .... " + emp.getEmpName());
System.out.println("Position .... " + emp.getPosition());
}
}
}
Exécution de l'exemple:
7. Get XML thành String
GetXmlAsString.java
package org.o7planning.jerseyrestclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class GetXmlAsString {
public static void main(String[] args) {
// Create Client
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees/E01");
ClientResponse response = webResource.accept("application/xml").get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
}
}
8. Get XML thành Object
GetXmlAsObject.java
package org.o7planning.jerseyrestclient;
import javax.ws.rs.core.MediaType;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class GetXmlAsObject {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
// Create Client based on Config
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees/E01");
Builder builder = webResource.accept(MediaType.APPLICATION_XML) //
.header("content-type", MediaType.APPLICATION_XML);
ClientResponse response = builder.get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
System.out.println("Output from Server .... \n");
Employee employee = (Employee) response.getEntity(Employee.class);
System.out.println("Emp No .... " + employee.getEmpNo());
System.out.println("Emp Name .... " + employee.getEmpName());
System.out.println("Position .... " + employee.getPosition());
}
}
9. Get XML thành List
L'exemple RESTful Web Service renvoie une List des objets.
@Path("/employees")
public class EmployeeService {
// URI:
// /contextPath/servletPath/employees
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> getEmployees() {
List<Employee> listOfCountries = EmployeeDAO.getAllEmployees();
return listOfCountries;
}
}
GetXmlAsList.java
package org.o7planning.jerseyrestclient;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class GetXmlAsList {
public static void main(String[] args) {
ClientConfig clientConfig = new DefaultClientConfig();
// Create Client based on Config
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
Builder builder = webResource.accept(MediaType.APPLICATION_XML) //
.header("content-type", MediaType.APPLICATION_XML);
ClientResponse response = builder.get(ClientResponse.class);
// Status 200 is successful.
if (response.getStatus() != 200) {
System.out.println("Failed with HTTP Error code: " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
GenericType<List<Employee>> generic = new GenericType<List<Employee>>() {
// No thing
};
List<Employee> list = response.getEntity(generic);
System.out.println("Output from Server .... \n");
for (Employee emp : list) {
System.out.println(" --- ");
System.out.println("Emp No .... " + emp.getEmpNo());
System.out.println("Emp Name .... " + emp.getEmpName());
System.out.println("Position .... " + emp.getPosition());
}
}
}
10. Post JSON
Utiliser POST demande au Web serivce pour créer une nouvelle ressource. Par exemple, ci- dessous crée un POST demande de joindre des données JSON afin de créer un nouveau Employee.
PostJsonString.java
package org.o7planning.jerseyrestclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class PostJsonString {
public static void main(String[] args) {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
// Data send to web service.
String input = "{\"empNo\":\"E01\",\"empName\":\"New Emp1\",\"position\":\"Manager\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
if (response.getStatus() != 200) {
System.out.println("Failed : HTTP error code : " + response.getStatus());
String error= response.getEntity(String.class);
System.out.println("Error: "+error);
return;
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
}
}
Exécution de l'exemple:
Jersey Client peut automatiquement convertir un objet Java en JSON ou XML pour envoyer avec la demande.
PostJsonObject.java
package org.o7planning.jerseyrestclient;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class PostJsonObject {
public static void main(String[] args) {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
// This object will be automatically converted into JSON
Employee newEmp = new Employee("E05", "New Emp1", "Manager");
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, newEmp);
if (response.getStatus() != 200) {
System.out.println("Failed : HTTP error code : " + response.getStatus());
String error = response.getEntity(String.class);
System.out.println("Error: " + error);
return;
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
}
}
11. Post XML
PostXmlString.java
package org.o7planning.jerseyrestclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class PostXmlString {
public static void main(String[] args) {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
// Data send to web service.
String input = "<employee>"//
+ "<empNo>E05</empNo>"//
+ "<empName>New Emp1</empName>"//
+ "<position>Manager</position>"
+ "</employee>";
// Send XML and receive XML
ClientResponse response = webResource.type("application/xml")//
.accept("application/xml")//
.post(ClientResponse.class, input);
if (response.getStatus() != 200) {
System.out.println("Failed : HTTP error code : " + response.getStatus());
String error = response.getEntity(String.class);
System.out.println("Error: " + error);
return;
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
}
}
Jersey Client peut automatiquement convertir un objet Java en JSON ou XML pour envoyer avec la demande.
PostXmlObject.java
package org.o7planning.jerseyrestclient;
import org.o7planning.jerseyrestclient.model.Employee;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class PostXmlObject {
public static void main(String[] args) {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/RESTfulCRUD/rest/employees");
// This object will be automatically converted into XML
Employee newEmp = new Employee("E05", "New Emp1", "Manager");
// Send XML and receive XML
ClientResponse response = webResource.type("application/xml")//
.accept("application/xml") //
.post(ClientResponse.class, newEmp);
if (response.getStatus() != 200) {
System.out.println("Failed : HTTP error code : " + response.getStatus());
String error = response.getEntity(String.class);
System.out.println("Error: " + error);
return;
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
}
}
Tutoriels Java Web Service
- Qu'est-ce que RESTful Web Service?
- Tutoriel Java RESTful Web Service pour débutant
- Exemple CRUD simple avec Java RESTful Web Service
- Créer Java RESTful Client avec Jersey Client
- RESTClient Un débogueur pour RESTful Web Service
- Exemple de CRUD simple avec Spring MVC RESTful Web Service
- Exemple CRUD Restful WebService avec Spring Boot
- Exemple Spring Boot Restful Client avec RestTemplate
- Sécurité Spring RESTful Service utilisant Basic Authentication
Show More