CXF web service client example

CXF Client overview

In previous chapter, we introduced get starting CXF web service example and CXF interceptor, CXF also provides you with many options to build CXF clients, today we will have quick view how to develop web Service client.


To start CXF client, the assumption is you have successfully developed web service and the WSDL(Web Services describe Language in XML format).

1. Generate java classes from WSDL file.

The WSDL2Java tool is able to generate JAX-WS client from your WSDL, it is very strongly typed interface. Alternatively, if you use IntelliJ IDEA IDE, please choose your project source code folder then right-click, select “web service->Generate Java code from WDDL or WADL” options.

Note: web service WSDL url specifics the CXF web service publishing address.

After generating, copy and import these new generated classes to your project and code as showed below:

SimpleWebService service = new SimpleWebService ();
SimpleWebServiceType client = service.getSimpleWebServicePort();
List< Attribute> result = client. getAttributes (
new getAttributes("atturibute","value"));

Now create the the web service:

JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
String wsdlPort = “http://localhost/SimpleWebService.wsdl”;
SimpleWebServiceType Type= (SimpleWebServiceType) factory.create();

The two way to implement web service client exactly have some differences, the first way you must hardcode your wsdlPort into class SimpleWebService,Like:

static {
URL url = null;
try {
  url = new URL("file:/E:/SimpleWebService.wsdl");
} catch (MalformedURLException e) {

But the second way can fit many different situations, it is very flexible to set wsdlPort to JaxWsProxyFactoryBean instance.

Using JAX-WS Proxy to implement CXF client

Instead of using a wsdl2java-generated stub client directly, you can use Service.create to create Service instances, the following code illustrates this process

URL wsdlURL = new URL("http://localhost/SimpleWebService.wsdl");
QName SERVICE_NAME = new QName("", "SOAPService");
Service service = Service.create(wsdlURL, SERVICE_NAME);
Greeter client = service.getPort(Greeter.class);
String result = client.greetMe("test");

Using JAX-WS Dispatch APIs to implement CXF client

JAX-WS dispatches APIs that allow dynamically invoke web service, which don’t need to generate a client code but allows to create messages and dispatch them.

import javax.xml.transform.Source;
URL wsdlURL = new URL("http://localhost/SimpleWebService.wsdl");
Service service = Service.create(wsdlURL, new QName("HelloService"));
Dispatch disp = service.createDispatch(new QName("HelloPort"), Source.class, Service.Mode.PAYLOAD);
Source request = new StreamSource("")
Source response = disp.invoke(request);...

Оцените статью
Добавить комментарий

Your email address will not be published. Required fields are marked *