从jersey-client-1.9升级到jersey-client-2.8

时间:2015-08-17 04:45:13

标签: jersey jersey-2.0 jersey-client

我正在使用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);

这有效......:)

1 个答案:

答案 0 :(得分:10)

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

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

在泽西岛2.x WebTarget类似于泽西岛1.x WebResource,而不是致电client.resource()来获取WebResource,而是致电client.target()得到WebTarget

WebTarget target = client.target(url); 

然后,您需要拨打request()上的WebTarget以获得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>2.8</version>
</dependency>

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

client.register(JacksonFeature.class);