Apache CXF Rest Client Clarity

时间:2013-09-04 17:08:22

标签: apache rest cxf jettison

我的要求是使用Apache CXF Rest Client API 供应商提供了网址http://test.com

Method: get
Url: /getDetails
Header set to application/json
and parameter z=12345

响应为JSON:

{
  "hasMore": "true",
  "results": [
    {
      "name": "ATM: 16th & Treemont",
      "phone": "(303) 249--‐9117",
      "streetAddress": "303 16th St. Suite 100"
    },
    {    
      "name": "ATM2:17th & Fremont",
      "phone": "(555) 999-98886",
      "streetAddress": "304 17th St. Suite 200"
    }
  ]
}

当我阅读客户端API的文档时,我看到了 链接: http://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-CXFWebClientAPI WebClient方法: 如果我按照这个例子,它描述了Book()如何根据我的要求描述Book对象?

WebClient client = WebClient.create("http://books");
client.path("bookstore/books");
client.type("text/xml").accept("text/xml")
Response r = client.post(new Book());
Book b = r.readEntity(Book.class);   

我也看到了Proxy的用法:它谈到BookStore.class ..这是服务器对象吗?如果是这样,我将无法在我的最后创建或拥有BookStore类或对象。

BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getBook();

我应该为我的回复创建一个类似于Book()的Object吗?我实际上必须从JSON响应中读取每个值(jettison)。 我应该采用哪种方法来处理我的需求,以及我该如何处理。我很困惑请建议。

我的要求是严格使用Apache CXF Rest API。

1 个答案:

答案 0 :(得分:3)

是。在客户端创建一个普通的pojo模型,类似于服务器端的Entity类,并根据需要使用相同的字段。 json也可以直接封送到对象。

假设我们使用Book模型

要检索ID为1的Book对象:

WebClient client = WebClient.create("http://localhost:8084/appname/rest/");

Book book = client.path("book/" + 1 ).accept("application/json").get(Book.class);

检索所有图书对象:

WebClient client = WebClient.create("http://localhost:8084/appname/rest/");


Set<Book> books = new HashSet<Book>(client.path("books/all").accept("application/json").getCollection(Book.class));

POST一个Book对象:

WebClient client = WebClient.create("http://localhost:8084/appname/rest/");

Book book = new Book();

book.setAuthor("Shiv);

book.setPublishedDate(new Date());

client.path("/book-post");

client.post(book); // Persist object

更新图书对象

WebClient client = WebClient.create("http://localhost:8084/appname/rest/");

Book book = client.path("book/" + 1 ).accept("application/json").get(Book.class);

book.setAuthor("Gopal);

book.setPublishedDate(new Date());

client.back(true);

client.path("/book-put");

client.put(book);// update book object

<强> NB

client.back(true)恢复为其余的API端点地址

client.path(String)将String值附加到端点地址