如何使用javax.ws.rs.client.WebTarget从REST客户端发送json对象

use*_*095 21 java rest jax-rs jersey-client jersey-2.0

我在下面给出了一个POJO,我希望将其作为JSON或XML输出到服务器.

这就是我所做的

客户:

ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(getBaseURI());

public void putFriend(String uri , Friend friend)
{
    System.out.println(friend.toString());

    target = target.path(some_path).path(uri);
    ClientResponse response =        target.request(MediaType.APPLICATION_JSON).put(Entity.entity(friend,MediaType.APPLICATION_JSON),ClientResponse.class);
}
Run Code Online (Sandbox Code Playgroud)

我在网上找到的例子是使用WebResource.

我不知道如何使用WebTarget.我所做的是从在SO上找到的一些示例中获取,但Entity.entity()给出了错误未定义的方法实体(friend,String).

POJO

@XmlRootElement
public class Friend{

    private String friendURI;
    private String event;
    private String uri;

    String getUri() {
        return uri;
    }
    void setUri(String uri) {
        this.uri = uri;
    }
    String getFriendURI() {
        return friendURI;
    }
    void setFriendURI(String friendURI) {
        this.friendURI = friendURI;
    }
    String getEvent() {
        return event;
    }
    void setEvent(String event) {
        this.event = event;
    }
public String toString() {
        return "Friend [friendURI=" + friendURI + ", uri=" + uri + ", event=" + event
                 + "]";
}
Run Code Online (Sandbox Code Playgroud)

请指导如何执行此操作.

谢谢

Pau*_*tha 46

有两个不同的泽西岛主要版本,1.x和2.x,你似乎试图使用两者的组合,这将无法正常工作.2.x版本没有1.x中的某些类,反之亦然.

如果你想使用Jersey 2.x,那么你应该使用Response,而不是ClientResponse

Response response = target.request().put(Entity.json(friend));
                                        // .json == automatic 'application/json'
Run Code Online (Sandbox Code Playgroud)

基本细分.

  • 确保`Entity`为[`javax.ws.rs.client.Entity`](https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/Entity.html) (2认同)