Consuming a Rest Web Service Example - Apache CXF Rest Client



This example explains how to implement a Rest Web Service Client using Apache CXF. Before running this application, please make sure a Rest Web Service is running in your machine and it should be available at
http://localhost:8080/apache_cxf_rest_ws/system/v1/address

Please refer Rest Web Services - Apache CXF for a rest Web Service example.

Following are the configuration and implementation details used in this example.

Step 1: Create Maven project

Following pom.xml defines the dependencies for this example.
		
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.smoothexample.pro</groupId> <artifactId>apache_cxf_rest_client</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>apache_cxf_rest_client</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <com.fasterxml.jackson.version>2.3.3</com.fasterxml.jackson.version> </properties> <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-rs-client</artifactId> <version>3.0.0-milestone1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>${com.fasterxml.jackson.version}</version> </dependency> </dependencies> </project>


Step 2:Create Web Service Client

Following Client application is used with the help of generated src using the above pom . Once everything is set up in eclipse you can see the generated src in target folder. Or you can run a maven build
		
package com.smoothexample.pro; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class AddressRestServiceClient { public static void main(String[] args) { Client client = ClientBuilder.newClient(); client.register(new JacksonJsonProvider()); WebTarget target = client.target("http://localhost:8080/apache_cxf_rest_ws/system/v1/address"); Invocation.Builder builder = target.request().accept("application/json"); Address address = builder.get().readEntity(Address.class); System.out.println(address.toString()); } }


Sample output

             	
Address [streetAddress=4800 abc Rd, addressOptional=addressOptional, city=abcd, state=NJ, country=US, zip=10001]