原文: https://howtodoinjava.com/jersey/jersey-restful-client-examples/
Jersey 2 客户端 API 从专有的 Jersey 1.x 客户端 API 中得到启发。 在此 Jersey 客户端示例中,我们将学习构建客户端 API 并调用不同的 REST 方法并使用 API 结果。
Table of Contents
1\. Jersey Client Maven
2\. Jersey ClientBuilder
3\. HTTP GET - Collection/List of Entities
4\. HTTP GET - Single Entity
5\. HTTP POST
6\. HTTP PUT
7\. HTTP DELETE
8\. Model classes and Configuration files
1. Jersey 客户端 Maven
在pom.xml
文件中添加 jersey 客户端 maven 依赖项。
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.25.1</version>
</dependency>
2. Jersey ClientBuilder
JAX-RS 客户端 API 设计为允许流畅的编程模型。 要创建 Jersey 客户端,请按照以下步骤操作:
- 使用
ClientBuilder.newClient()
静态方法。 - 在上面获得的客户端实例上使用
client.target()
方法。 - 在第二步中获得的
WebTarget
实例上,使用webTarget.request()
方法获取Invocation.Builder
。 - 执行
invocationBuilder.get()
,put()
,post()
或delete()
方法以调用相应的 REST API。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.post(Entity.entity(emp, MediaType.APPLICATION_XML));
下面给出的示例将有助于我们更好地理解并为开发任务做好准备。 我建议您浏览其他 Jersey 示例,例如文件上传示例和文件下载示例。
3. HTTP GET – 实体的集合/列表
REST API
这是用于检索系统中所有员工的 API 代码。
@GET
@Path("/employees")
@Produces(MediaType.APPLICATION_XML)
public Employees getAllEmployees()
{
Employees list = new Employees();
list.setEmployeeList(new ArrayList<Employee>());
list.getEmployeeList().add(new Employee(1, "Lokesh Gupta"));
list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey"));
list.getEmployeeList().add(new Employee(3, "David Kameron"));
return list;
}
Jersey 客户端代码
此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.get();
Employees employees = response.readEntity(Employees.class);
List<Employee> listOfEmployees = employees.getEmployeeList();
System.out.println(response.getStatus());
System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) ));
Output:
200
[Employee [id=1, name=Lokesh Gupta], Employee [id=2, name=Alex Kolenchiskey], Employee [id=3, name=David Kameron]]
4. HTTP GET – 单一实体
这是 API 代码,用于根据其 ID 检索单个员工。
@GET
@Path("/employees/{id}")
@Produces(MediaType.APPLICATION_XML)
public Response updateEmployeeById(@PathParam("id") Integer id)
{
if(id < 0){
return Response.noContent().build();
}
Employee emp = new Employee();
emp.setId(id);
emp.setName("Lokesh Gupta");
GenericEntity<Employee> entity = new GenericEntity<Employee>(emp, Employee.class);
return Response.ok().entity(entity).build();
}
客户端代码
此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.get();
Employee employee = response.readEntity(Employee.class);
System.out.println(response.getStatus());
System.out.println(employee);
Output:
200
Employee [id=1, name=Lokesh Gupta]
5. HTTP POST
这是用于在集合中添加员工的 API 代码。
@POST
@Path("/employees")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response addEmployee( Employee e ) throws URISyntaxException
{
if(e == null){
return Response.status(400).entity("Please add employee details !!").build();
}
if(e.getName() == null) {
return Response.status(400).entity("Please provide the employee name !!").build();
}
return Response.created(new URI("/rest/employees/"+e.getId())).build();
}
Jersey 客户端代码
此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
Employee emp = new Employee();
emp.setId(1);
emp.setName("David Feezor");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.post(Entity.entity(emp, MediaType.APPLICATION_XML));
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
Output:
201
6. HTTP PUT
这是 API 代码,用于通过其 ID 更新员工名称。
@PUT
@Path("/employees/{id}")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response updateEmployeeById(@PathParam("id") Integer id, Employee e)
{
Employee updatedEmployee = new Employee();
if(e.getName() == null) {
return Response.status(400).entity("Please provide the employee name !!").build();
}
updatedEmployee.setId(id);
updatedEmployee.setName(e.getName());
return Response.ok().entity(updatedEmployee).build();
}
Jersey2 客户端代码
此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
Employee emp = new Employee();
emp.setId(1);
emp.setName("David Feezor");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
Employee employee = response.readEntity(Employee.class);
System.out.println(response.getStatus());
System.out.println(employee);
Output:
200
Employee [id=1, name=David Feezor]
7. HTTP DELETE
这是用于通过 ID 从集合中删除员工的 API 代码。
@DELETE
@Path("/employees/{id}")
public Response deleteEmployeeById(@PathParam("id") Integer id)
{
return Response.status(202).entity("Employee deleted successfully !!").build();
}
Jersey 客户端代码
此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
Invocation.Builder invocationBuilder = webTarget.request();
Response response = invocationBuilder.delete();
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
Output:
202
Employee deleted successfully !!
8. 模型类和配置文件
下面列出了其他用于创建此 Jersey2 客户端示例的文件。
Employees.java
package com.howtodoinjava.jersey;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "employeeList")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employees
{
@XmlElement(name="employee")
private List<Employee> employeeList;
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
}
Employee.java
package com.howtodoinjava.jersey;
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 Integer id;
private String name;
public Employee() {
}
public Employee(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}
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>com.howtodoinjava.jersey</groupId>
<artifactId>JerseyDemos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
<properties>
<jersey2.version>2.19</jersey2.version>
<jaxrs.version>2.0.1</jaxrs.version>
</properties>
<dependencies>
<!-- JAX-RS -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${jaxrs.version}</version>
</dependency>
<!-- Jersey2.19 -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey2.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>JerseyDemos</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<!DOCTYPE web-app PUBLIC
"-//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.howtodoinjava.jersey</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter</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>
在下面将您的问题和评论发送给我。
学习愉快!
参考: