In this blog I am going to talk
about Java client for Rest Services. Here we will take CXF implementation and
go through various ways of invoking Rest Services.
Following are various options for
creating CXF client
- Injecting proxies
- Proxy-based API
- Web Clients
Injecting
proxies
CXF has deepest
integration with Spring.Here the client Id will work exactly like
Bean and when you
use the bean definition form bean
factory It will work as It
is getting called from
the same location.
<jaxrs:client
id="restClient"
address="http://localhost:${bookstore.restlocation.url}/services/bookservice/get"
serviceClass="com.bookstore.client.BookStoreInterface"
inheritHeaders="true">
<jaxrs:headers>
<entry key="Accept"
value="text/xml"/>
</jaxrs:headers>
</jaxrs:client>
Proxy-based API
BookStore
store = JAXRSClientFactory.create("http://bookstore.com",
BookStore.class);
//Customization
WebClient.client(proxy).accept("text/xml");
//
(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();
proxies to Web
Clients
BookStore
proxy = JAXRSClientFactory.create("http://books", BookStore.class);
Client
client = WebClient.client(proxy);
WebClient
httpClient = WebClient.fromClient(client);
Web Clients
WebClient
client = WebClient.create("http://books");
Book
book = client.path("bookstore/books").accept("text/xml").get(Book.class);
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);
Configuring
HTTP clients in Spring
<bean id="myWebClient" class="org.apache.cxf.jaxrs.client.WebClient"
factory-method="create">
<constructor-arg type="java.lang.String"
value="http://some.base.url.that.responds/" />
<constructor-arg ref="webClientProviders" />
</bean>
In
the next Blog for CXF will discuss the advanced topics like asynchronous call,
thread safety and other things.
For more detailed Information refer to CXF project documentation on http://cxf.apache.org/docs/jax-rs-client-api.html
Nice one. Any update regarding the last part "In the next Blog for CXF will discuss the advanced topics like asynchronous call, thread safety and other things.". This section "Asynchronous Client HTTP Transport" in CXF is really lacking.
ReplyDelete