正在从 Jersey 客户端 1.x 升级到 Jersey 客户端 2.x

Upgrading from Jersey Client 1.x to Jersey Client 2.x

我正在使用 jersey-client-1.9。示例代码:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

Client client = Client.create();
webResource = client.resource("http://localhost:8047/storage/hive.json");
String input = //rest request
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
String queryRespose = response.getEntity(String.class);

因为这个项目已经从com.sun.jersey.api.client变成了org.glassfish.jersey.client。如何在 jersey-client-2.8 中实现这一目标?

编辑:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8047/query.json");
String input =//rest request
Response response = target.request().post(Entity.json(input));
String queryRespose = response.readEntity(String.class);

这有效...:)

使用 Jersey 2.x,您可以使用 ClientBuilder

构建 Client
Client client = ClientBuilder.newClient();

在 Jersey 2.x WebTarget 中类似于 Jersey 1.x WebResource,而不是调用 client.resource() 来获取 WebResource,你打电话给 client.target() 得到 WebTarget

WebTarget target = client.target(url); 

然后您需要在 WebTarget 上调用 request() 以获得 Invocation.Builder,这将允许您链接其他调用

Invocation.Builder invocation = target.request();

要发送实体,我们需要将 Entity 传递给 Invocation.Builder 的请求方法之一。例如

Response response = builder.post(Entity.json(input);

要阅读回复,请使用 response.readEntity(String.class)。所以总的来说,你可以做

Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().post(Entity.json(input));
String entity = response.readEntity(String.class);

另请参阅:


更新

您可能还需要以下依赖项来支持 JSON/POJO

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>${jersey.version}</version>
</dependency>

然后向客户端注册JacksonFeature。这样 input(如果你想使用 POJO 而不是 String)可以序列化为 JSON

client.register(JacksonFeature.class);