简体   繁体   English

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

[英]how to send json object from REST client using javax.ws.rs.client.WebTarget

I have a POJO given below which I want to PUT to the server as JSON or XML. 我在下面给出了一个POJO,我希望将其作为JSON或XML输出到服务器。

This is what I have done 这就是我所做的

CLIENT: 客户:

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);
}

Examples I found on web were using WebResource. 我在网上找到的例子是使用WebResource。

I don't know how to do using WebTarget. 我不知道如何使用WebTarget。 What I have done is taken from some example found on SO but Entity.entity() gives error undefined method entity(friend, String). 我所做的是从在SO上找到的一些示例中获取,但Entity.entity()给出了错误未定义的方法实体(friend,String)。

POJO 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
                 + "]";
}

Please guide how to do this. 请指导如何执行此操作。

Thanks 谢谢

There are two different Jersey major versions, 1.x and 2.x, You seems to be trying to use a combination of both, which won't work. 有两个不同的泽西岛主要版本,1.x和2.x,你似乎试图使用两者的组合,这是行不通的。 The 2.x versions don't have some classes as in 1.x and vice versa. 2.x版本没有1.x中的某些类,反之亦然。

If you want to use Jersey 2.x, then you should be using Response , rather than ClientResponse 如果你想使用Jersey 2.x,那么你应该使用Response而不是ClientResponse

Response response = target.request().put(Entity.json(friend));
                                        // .json == automatic 'application/json'

Basic breakdown. 基本细分。

  • Calling request() on WebTarget returns an Invocation.Buidler WebTarget上调用request() WebTarget返回一个Invocation.Buidler

     Invocation.Builder builder = target.request(); 
  • Once we call put , we get back a Response 一旦我们调用put ,我们就会回复一个Response

     Response response = builder.put(Entity.json(friend)); 
  • To extract a known type from the response, we could use readEntity(Class type) 要从响应中提取已知类型,我们可以使用readEntity(Class type)

     String responseString = response.readEntity(String.class); response.close(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM