Thursday, 5 May 2011

CXF | JAX-RS | REST client

JAX-RS (Java API for RESTful Web Services) is an API specification for creating web services in the REST format.

First step is to create the client factory bean:
JAXRSClientFactoryBean clientFactoryBean = new JAXRSClientFactoryBean();
Set url of the web service and the service class definition like this:
clientFactoryBean.setResourceClass(OrderService.class);
clientFactoryBean.setAddress("http://example.com");
Create binding factory:
JAXRSBindingFactory bindingFactory = new JAXRSBindingFactory();
bindingFactory.setBus(clientFactoryBean.getBus());
Register binding factory for JAX-RS:
BindingFactoryManager bindingManager = clientFactoryBean.getBus().getExtension(BindingFactoryManager.class);
bindingManager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, bindingFactory);
Create web client to access service APIs.
WebClient webClient = clientFactoryBean.createWebClient();
Add authentication if any to the web client header.
String authorizationHeader = "Basic " + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());
webClient.header("Authorization", authorizationHeader);
Get response(order) from the web client.
Order order = webClient.path("order/orders").accept("text/xml").get(Order.class);
System.out.println("Order ID : "+order.getOrderID());

No comments:

Post a Comment