原文: https://howtodoinjava.com/jersey/jersey-restful-client-examples/

Jersey 2 客户端 API 从专有的 Jersey 1.x 客户端 API 中得到启发。 在此 Jersey 客户端示例中,我们将学习构建客户端 API 并调用不同的 REST 方法并使用 API 结果。

  1. Table of Contents
  2. 1\. Jersey Client Maven
  3. 2\. Jersey ClientBuilder
  4. 3\. HTTP GET - Collection/List of Entities
  5. 4\. HTTP GET - Single Entity
  6. 5\. HTTP POST
  7. 6\. HTTP PUT
  8. 7\. HTTP DELETE
  9. 8\. Model classes and Configuration files

1. Jersey 客户端 Maven

pom.xml文件中添加 jersey 客户端 maven 依赖项。

  1. <dependency>
  2. <groupId>org.glassfish.jersey.core</groupId>
  3. <artifactId>jersey-client</artifactId>
  4. <version>2.25.1</version>
  5. </dependency>

2. Jersey ClientBuilder

JAX-RS 客户端 API 设计为允许流畅的编程模型。 要创建 Jersey 客户端,请按照以下步骤操作:

  1. 使用ClientBuilder.newClient()静态方法。
  2. 在上面获得的客户端实例上使用client.target()方法。
  3. 在第二步中获得的WebTarget实例上,使用webTarget.request()方法获取Invocation.Builder
  4. 执行invocationBuilder.get()put()post()delete()方法以调用相应的 REST API。
  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
  3. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
  4. Response response = invocationBuilder.post(Entity.entity(emp, MediaType.APPLICATION_XML));

下面给出的示例将有助于我们更好地理解并为开发任务做好准备。 我建议您浏览其他 Jersey 示例,例如文件上传示例文件下载示例

3. HTTP GET – 实体的集合/列表

REST API

这是用于检索系统中所有员工的 API 代码。

  1. @GET
  2. @Path("/employees")
  3. @Produces(MediaType.APPLICATION_XML)
  4. public Employees getAllEmployees()
  5. {
  6. Employees list = new Employees();
  7. list.setEmployeeList(new ArrayList<Employee>());
  8. list.getEmployeeList().add(new Employee(1, "Lokesh Gupta"));
  9. list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey"));
  10. list.getEmployeeList().add(new Employee(3, "David Kameron"));
  11. return list;
  12. }

Jersey 客户端代码

此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
  3. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
  4. Response response = invocationBuilder.get();
  5. Employees employees = response.readEntity(Employees.class);
  6. List<Employee> listOfEmployees = employees.getEmployeeList();
  7. System.out.println(response.getStatus());
  8. System.out.println(Arrays.toString( listOfEmployees.toArray(new Employee[listOfEmployees.size()]) ));
  9. Output:
  10. 200
  11. [Employee [id=1, name=Lokesh Gupta], Employee [id=2, name=Alex Kolenchiskey], Employee [id=3, name=David Kameron]]

4. HTTP GET – 单一实体

这是 API 代码,用于根据其 ID 检索单个员工。

  1. @GET
  2. @Path("/employees/{id}")
  3. @Produces(MediaType.APPLICATION_XML)
  4. public Response updateEmployeeById(@PathParam("id") Integer id)
  5. {
  6. if(id < 0){
  7. return Response.noContent().build();
  8. }
  9. Employee emp = new Employee();
  10. emp.setId(id);
  11. emp.setName("Lokesh Gupta");
  12. GenericEntity<Employee> entity = new GenericEntity<Employee>(emp, Employee.class);
  13. return Response.ok().entity(entity).build();
  14. }

客户端代码

此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
  3. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
  4. Response response = invocationBuilder.get();
  5. Employee employee = response.readEntity(Employee.class);
  6. System.out.println(response.getStatus());
  7. System.out.println(employee);
  8. Output:
  9. 200
  10. Employee [id=1, name=Lokesh Gupta]

5. HTTP POST

这是用于在集合中添加员工的 API 代码。

  1. @POST
  2. @Path("/employees")
  3. @Consumes(MediaType.APPLICATION_XML)
  4. @Produces(MediaType.APPLICATION_XML)
  5. public Response addEmployee( Employee e ) throws URISyntaxException
  6. {
  7. if(e == null){
  8. return Response.status(400).entity("Please add employee details !!").build();
  9. }
  10. if(e.getName() == null) {
  11. return Response.status(400).entity("Please provide the employee name !!").build();
  12. }
  13. return Response.created(new URI("/rest/employees/"+e.getId())).build();
  14. }

Jersey 客户端代码

此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees");
  3. Employee emp = new Employee();
  4. emp.setId(1);
  5. emp.setName("David Feezor");
  6. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
  7. Response response = invocationBuilder.post(Entity.entity(emp, MediaType.APPLICATION_XML));
  8. System.out.println(response.getStatus());
  9. System.out.println(response.readEntity(String.class));
  10. Output:
  11. 201

6. HTTP PUT

这是 API 代码,用于通过其 ID 更新员工名称。

  1. @PUT
  2. @Path("/employees/{id}")
  3. @Consumes(MediaType.APPLICATION_XML)
  4. @Produces(MediaType.APPLICATION_XML)
  5. public Response updateEmployeeById(@PathParam("id") Integer id, Employee e)
  6. {
  7. Employee updatedEmployee = new Employee();
  8. if(e.getName() == null) {
  9. return Response.status(400).entity("Please provide the employee name !!").build();
  10. }
  11. updatedEmployee.setId(id);
  12. updatedEmployee.setName(e.getName());
  13. return Response.ok().entity(updatedEmployee).build();
  14. }

Jersey2 客户端代码

此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
  3. Employee emp = new Employee();
  4. emp.setId(1);
  5. emp.setName("David Feezor");
  6. Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_XML);
  7. Response response = invocationBuilder.put(Entity.entity(emp, MediaType.APPLICATION_XML));
  8. Employee employee = response.readEntity(Employee.class);
  9. System.out.println(response.getStatus());
  10. System.out.println(employee);
  11. Output:
  12. 200
  13. Employee [id=1, name=David Feezor]

7. HTTP DELETE

这是用于通过 ID 从集合中删除员工的 API 代码。

  1. @DELETE
  2. @Path("/employees/{id}")
  3. public Response deleteEmployeeById(@PathParam("id") Integer id)
  4. {
  5. return Response.status(202).entity("Employee deleted successfully !!").build();
  6. }

Jersey 客户端代码

此 RESTful 客户端代码将访问上述 API,并在控制台中打印响应。

  1. Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class ) );
  2. WebTarget webTarget = client.target("http://localhost:8080/JerseyDemos/rest").path("employees").path("1");
  3. Invocation.Builder invocationBuilder = webTarget.request();
  4. Response response = invocationBuilder.delete();
  5. System.out.println(response.getStatus());
  6. System.out.println(response.readEntity(String.class));
  7. Output:
  8. 202
  9. Employee deleted successfully !!

8. 模型类和配置文件

下面列出了其他用于创建此 Jersey2 客户端示例的文件。

Employees.java

  1. package com.howtodoinjava.jersey;
  2. import java.util.List;
  3. import javax.xml.bind.annotation.XmlAccessType;
  4. import javax.xml.bind.annotation.XmlAccessorType;
  5. import javax.xml.bind.annotation.XmlElement;
  6. import javax.xml.bind.annotation.XmlRootElement;
  7. @XmlRootElement(name = "employeeList")
  8. @XmlAccessorType (XmlAccessType.FIELD)
  9. public class Employees
  10. {
  11. @XmlElement(name="employee")
  12. private List<Employee> employeeList;
  13. public List<Employee> getEmployeeList() {
  14. return employeeList;
  15. }
  16. public void setEmployeeList(List<Employee> employeeList) {
  17. this.employeeList = employeeList;
  18. }
  19. }

Employee.java

  1. package com.howtodoinjava.jersey;
  2. import javax.xml.bind.annotation.XmlAccessType;
  3. import javax.xml.bind.annotation.XmlAccessorType;
  4. import javax.xml.bind.annotation.XmlRootElement;
  5. @XmlRootElement(name = "employee")
  6. @XmlAccessorType (XmlAccessType.FIELD)
  7. public class Employee
  8. {
  9. private Integer id;
  10. private String name;
  11. public Employee() {
  12. }
  13. public Employee(Integer id, String name) {
  14. this.id = id;
  15. this.name = name;
  16. }
  17. public Integer getId() {
  18. return id;
  19. }
  20. public void setId(Integer id) {
  21. this.id = id;
  22. }
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. @Override
  30. public String toString() {
  31. return "Employee [id=" + id + ", name=" + name + "]";
  32. }
  33. }

pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.howtodoinjava.jersey</groupId>
  5. <artifactId>JerseyDemos</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>war</packaging>
  8. <repositories>
  9. <repository>
  10. <id>maven2-repository.java.net</id>
  11. <name>Java.net Repository for Maven</name>
  12. <url>http://download.java.net/maven/2/</url>
  13. <layout>default</layout>
  14. </repository>
  15. </repositories>
  16. <properties>
  17. <jersey2.version>2.19</jersey2.version>
  18. <jaxrs.version>2.0.1</jaxrs.version>
  19. </properties>
  20. <dependencies>
  21. <!-- JAX-RS -->
  22. <dependency>
  23. <groupId>javax.ws.rs</groupId>
  24. <artifactId>javax.ws.rs-api</artifactId>
  25. <version>${jaxrs.version}</version>
  26. </dependency>
  27. <!-- Jersey2.19 -->
  28. <dependency>
  29. <groupId>org.glassfish.jersey.containers</groupId>
  30. <artifactId>jersey-container-servlet</artifactId>
  31. <version>${jersey2.version}</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.glassfish.jersey.core</groupId>
  35. <artifactId>jersey-server</artifactId>
  36. <version>${jersey2.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.glassfish.jersey.core</groupId>
  40. <artifactId>jersey-client</artifactId>
  41. <version>${jersey2.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.glassfish.jersey.media</groupId>
  45. <artifactId>jersey-media-multipart</artifactId>
  46. <version>${jersey2.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>com.fasterxml.jackson.jaxrs</groupId>
  50. <artifactId>jackson-jaxrs-json-provider</artifactId>
  51. <version>2.4.1</version>
  52. </dependency>
  53. </dependencies>
  54. <build>
  55. <finalName>JerseyDemos</finalName>
  56. <plugins>
  57. <plugin>
  58. <artifactId>maven-compiler-plugin</artifactId>
  59. <configuration>
  60. <source>1.7</source>
  61. <target>1.7</target>
  62. </configuration>
  63. </plugin>
  64. </plugins>
  65. </build>
  66. </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>

在下面将您的问题和评论发送给我。

学习愉快!

参考:

Jersey 客户端 Java 文档