JAX-RS Client with Jersey – 带有Jersey的JAX-RS客户端

最后修改: 2017年 2月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Jersey is an open source framework for developing RESTFul Web Services. It also has great inbuilt client capabilities.

Jersey是一个用于开发RESTFul Web服务的开源框架。它还具有强大的内置客户端功能。

In this quick tutorial, we will explore the creation of JAX-RS client using Jersey 2.

在这个快速教程中,我们将探讨使用Jersey 2创建JAX-RS客户端。

For a discussion on the creation of RESTful Web Services using Jersey, please refer to this article.

关于使用Jersey创建RESTful Web服务的讨论,请参考这篇文章

2. Maven Dependencies

2.Maven的依赖性

Let’s begin by adding the required dependencies (for Jersey JAX-RS client) in the pom.xml:

让我们首先在pom.xml中添加所需的依赖项(针对Jersey JAX-RS客户端)。

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.25.1</version>
</dependency>

To use Jackson 2.x as JSON provider:

要使用Jackson 2.x作为JSON提供者。

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.25.1</version>
</dependency>

The latest version of these dependencies can be found at jersey-client and jersey-media-json-jackson.

这些依赖的最新版本可以在jersey-clientjersey-media-jon-jackson找到。

3. RESTFul Client in Jersey

3.泽西岛的RESTFul客户

We will develop a JAX-RS client to consume the JSON and XML REST APIs that we developed here (we need to make sure that the service is deployed and the URL is accessible).

我们将开发一个JAX-RS客户端来消费我们开发的这里的JSON和XML REST API(我们需要确保服务已经部署并且URL可以访问)。

3.1. Resource Representation Class

3.1.资源表示类

Let’s have a look at the resource representation class:

让我们看一下资源表示类。

@XmlRootElement
public class Employee {
    private int id;
    private String firstName;

    // standard getters and setters
}

JAXB annotations like @XmlRootElement are required only if XML support is needed.

只有在需要 XML 支持时,才需要像 @XmlRootElement 这样的 JAXB 注解。

3.2. Creating an Instance of a Client

3.2.创建一个客户端的实例

The first thing we need is an instance of a Client:

我们首先需要的是一个Client的实例。

Client client = ClientBuilder.newClient();

3.3. Creating a WebTarget

3.3.创建一个WebTarget

Once we have the Client instance, we can create a WebTarget using the URI of the targeted web resource:

一旦我们有了Client实例,我们就可以使用目标网络资源的URI创建一个WebTarget

WebTarget webTarget 
  = client.target("http://localhost:8082/spring-jersey");

Using WebTarget, we can define a path to a specific resource:

使用WebTarget,我们可以定义一个通往特定资源的路径。

WebTarget employeeWebTarget 
  = webTarget.path("resources/employees");

3.4. Building an HTTP Request Invocation

3.4.建立一个HTTP请求调用

An invocation builder instance is created one of the WebTarget.request() methods:

一个调用构建器实例是由WebTarget.request()方法之一创建的。

Invocation.Builder invocationBuilder 
  = employeeWebTarget.request(MediaType.APPLICATION_JSON);

For XML format, MediaType.APPLICATION_XML can be used.

对于XML格式,可以使用MediaType.APPLICATION_XML

3.5. Invoking HTTP Requests

3.5.调用HTTP请求

Invoking HTTP GET:

调用HTTP GET。

Response response 
  = invocationBuilder.get(Employee.class);

Invoking HTTP POST:

调用HTTP POST。

Response response 
  = invocationBuilder
  .post(Entity.entity(employee, MediaType.APPLICATION_JSON);

3.6. Sample REST Client

3.6.REST客户端示例

Let’s begin writing a simple REST client. The getJsonEmployee() method retrieves an Employee object based on the employee id. The JSON returned by the REST Web Service is deserialized to the Employee object before returning.

让我们开始编写一个简单的REST客户端。getJsonEmployee()方法根据雇员id检索一个Employee对象。由REST Web Service返回的JSON在返回之前被反序列化为Employee对象。

Using the JAX-RS API fluently to create web target, invocation builder and invoking a GET HTTP request:

流畅地使用JAX-RS API来创建网络目标、调用构建器和调用GET HTTP请求。

public class RestClient {
 
    private static final String REST_URI 
      = "http://localhost:8082/spring-jersey/resources/employees";
 
    private Client client = ClientBuilder.newClient();

    public Employee getJsonEmployee(int id) {
        return client
          .target(REST_URI)
          .path(String.valueOf(id))
          .request(MediaType.APPLICATION_JSON)
          .get(Employee.class);
    }
    //...
}

Let’s now add a method for POST HTTP request. The createJsonEmployee() method creates an Employee by invoking the REST Web Service for Employee creation. The client API internally serializes the Employee object to JSON before invoking the HTTP POST method:

现在让我们添加一个POST HTTP请求的方法。createJsonEmployee()方法通过调用REST Web Service来创建Employee,从而创建一个Employee。客户端API在内部将Employee对象序列化为JSON,然后调用HTTP POST方法。

public Response createJsonEmployee(Employee emp) {
    return client
      .target(REST_URI)
      .request(MediaType.APPLICATION_JSON)
      .post(Entity.entity(emp, MediaType.APPLICATION_JSON));
}

4. Testing the Client

4.测试客户

Let’s test our client with JUnit:

让我们用JUnit测试我们的客户端。

public class JerseyClientLiveTest {
 
    public static final int HTTP_CREATED = 201;
    private RestClient client = new RestClient();

    @Test
    public void givenCorrectObject_whenCorrectJsonRequest_thenResponseCodeCreated() {
        Employee emp = new Employee(6, "Johny");

        Response response = client.createJsonEmployee(emp);

        assertEquals(response.getStatus(), HTTP_CREATED);
    }
}

5. Conclusion

5.结论

In this article, we have introduced JAX-RS client using Jersey 2 and developed a simple RESTFul Java client.

在这篇文章中,我们使用Jersey 2介绍了JAX-RS客户端,并开发了一个简单的RESTFul Java客户端。

As always, the full source code is available in this Github project.

一如既往,完整的源代码可在这个Github项目中获得。