1. 概述
Jersey 是一個開源框架,用於開發 RESTful Web 服務。它還具有強大的內置客户端功能。
在本快速教程中,我們將探索使用 Jersey 2 創建 JAX-RS 客户端。
有關使用 Jersey 創建 RESTful Web 服務的內容,請參閲本文。
2. Maven 依賴項
我們首先在 pom.xml 中添加所需的依賴項(用於 Jersey JAX-RS 客户端):
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.25.1</version>
</dependency>
為了使用 Jackson 2.x 作為 JSON 提供程序:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
這些依賴項的最新版本可以在 jersey-client 和 jersey-media-json-jackson 找到。
3. RESTFul Client in Jersey
我們將開發一個 JAX-RS 客户端來消費我們開發的 JSON 和 XML REST API(我們需要確保服務已部署且 URL 可訪問)。
3.1. Resource Representation Class
讓我們看一下資源表示類:
@XmlRootElement
public class Employee {
private int id;
private String firstName;
// standard getters and setters
}
JAXB 註解如
3.2. Creating an Instance of a Client
首先我們需要一個
Client client = ClientBuilder.newClient();
3.3. Creating a WebTarget
在獲得
WebTarget webTarget
= client.target("http://localhost:8082/spring-jersey/");
使用
WebTarget employeeWebTarget
= webTarget.path("resources/employees");
3.4. Building an HTTP Request Invocation
創建了一個
Invocation.Builder invocationBuilder
= employeeWebTarget.request(MediaType.APPLICATION_JSON);
對於 XML 格式,可以使用
3.5. Invoking HTTP Requests
調用 HTTP GET:
Response response
= invocationBuilder.get(Employee.class);
調用 HTTP POST:
Response response
= invocationBuilder
.post(Entity.entity(employee, MediaType.APPLICATION_JSON));
3.6. Sample REST Client
讓我們開始編寫一個簡單的 REST 客户端。
使用 JAX-RS API 順暢地創建 Web 目標、調用構建器和調用 HTTP GET 請求:
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);
}
//...
}
現在我們添加一個用於 POST HTTP 請求的方法。
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
讓我們使用 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. 結論
在本文中,我們介紹了使用 Jersey 2 和 Java 客户端構建了一個簡單的 RESTful Java 客户端。