Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


 

 

 

 

...

Span
stylefont-size:2em;font-weight:bold
JAX-RS : Client API

...

 

 

 

...


Table of Contents

Maven Dependency

Code Block
xml
xml
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-rs-client</artifactId>
  <version>3.0.0-milestone1<15</version>
</dependency>

In CXF 2.7.x no JAX-RS 2.0 Client API is supported and CXF specific Client API is located in the cxf-rt-frontend-jaxrs module.

...

Code Block
xml
xml
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-transports-http-hc</artifactId>
  <!-- 2.7.8 or 3.0.0-milestone115 --> 
  <version>${cxf.version}</version>
</dependency>

...

Code Block
java
java
@Path("/bookstore")
public interface BookStore {
   @GET
   Books getAllBooks();
   
   @Path("{id}")
   BookResource getBookSubresource(@PathParam("id") long id) throws NoBookFoundException;
}

public class BookStoreImpl implements BookStore {
   public Books getAllBooks() {}
   
   public BookBookResource getBookSubresource(long id) throws NoBookFoundException {}
}

public interface BookResource {
   @GET
   Book getBook();
}

public class BookResourceImpl implements BookResource {
   Book getBook() {}
}

...

For injecting proxies via a spring context, use the jaxrs:client element like:

Code Block
xml
xml
  <jaxrs:client id="restClient"
         address="http://localhost:${testutil.ports.BookServerRestSoap}/test/services/rest"
         serviceClass="org.apache.cxf.systest.jaxrs.BookStoreJaxrsJaxws"
         inheritHeaders="true">
         <jaxrs:headers>
             <entry key="Accept" value="text/xml"/>
         </jaxrs:headers>
  </jaxrs:client>  

See this bean for a full example of how jaxrs:client can be used to inject a proxy

Limitations

Proxy sub-resource methods returning Objects can not be invoked. Prefer to have sub-resource methods returning typed classes: interfaces, abstract classes or concrete implementations.

The following applies to CXF 2.6.x-2.4.x only:

When a proxy method returning a JAX-RS Response is invoked, the returned Response.getEntity() will return a response InputStream by default. Starting with CXF 2.3.2 one can register an org.apache.cxf.jaxrs.client.ResponseReader provider and cast the Response.getEntity() to more specific application classes:

...

ResponseReader reader = new ResponseReader();
reader.setEntityClass(Book.class);
        
BookStore bs = JAXRSClientFactory.create("http://localhost:8080/books", BookStore.class,
                                         Collections.singletonList(reader));
Response r1 = bs.getBook("123");
Book book = (Book)r1.getEntity();

reader.setEntityClass(Author.class);
Response r2 = bs.getBookAuthor("123");
Author book = (Author)r2.getEntity();

. Note that WebClient can also be injected as a jaxrs:client.


Asynchronous proxy invocations

Starting from CXF 3.1.7 it is possible to do the asynchronous proxy invocations. One needs to register JAX-RS 2.0 InvocationCallback as a proxy request context property:

Code Block
java
java
BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class);

Book book = null;
final InvocationCallback<Book> callback = new InvocationCallback<Book>() {
  public void completed(Book response) {
     book = response;
  }
  public void failed(Throwable error) {
  }
};


WebClient.getConfig(proxy).getRequestContext().put(InvocationCallback.class.getName(), callback);
assertNull(proxy.getBook());
Thread.sleep(3);
assertNotNull(book);

If you have a proxy with different methods returning different response types then either register an Object bound InvocationCallback or register a collection of type-specific callbacks

Working with user models

Proxies can be created with the external user model being applied to a proxy class, for example:

Code Block
java
java
BookStore proxy = JAXRSClientFactory.createFromModelcreate("http://books", BookNoAnnotationsBookStore.class, "classpath:/resources/model.xml", null);

BookNoAnnotations is either an interface or concrete class with no JAX-RS annotations. Both client proxies and server endpoints can 'turn' it into a RESTful resource by applying an external user model.

CXF WebClient API

);

// Book
Book book = null;
final InvocationCallback<Book> bookCallback = new InvocationCallback<Book>() {
  public void completed(Book response) {
     book = response;
  }
  public void failed(Throwable error) {
  }
};
// Chapter
Chapter chapter = null;
final InvocationCallback<Chapter> chapterCallback = new InvocationCallback<Chapter>() {
  public void completed(Chapter response) {
     chapter = response;
  }
  public void failed(Throwable error) {
  }
};
 
WebClient.getConfig(proxy).getRequestContext().put(InvocationCallback.class.getName(), 
                                                   Arrays.asList(bookCallback, chapterCallback));
// Get Book
assertNull(proxy.getBook(123L));
Thread.sleep(3);
assertNotNull(book);
 
// Get Book Chapter
assertNull(proxy.getBookChapter(123L));
Thread.sleep(3);
assertNotNull(chapter);

Make sure a proxy is created in a thread safe mode if it is being accessed by multiple threads for every new request thread to have its own callback.

Buffering Responses

One way to buffer proxy responses is to have a proxy method return JAX-RS Response, use its bufferEntity()  method (available in JAX-RS 2.0) and use Response.readEntity which can return typed responses if preferred.

The other option is to have a "buffer.proxy.response" property enabled on a given proxy instance.

Limitations

Proxy sub-resource methods returning Objects can not be invoked. Prefer to have sub-resource methods returning typed classes: interfaces, abstract classes or concrete implementations.


Working with user models

Proxies can be created with the external user model being applied to a proxy class, for example:

Code Block
java
java
JAXRSClientFactory.createFromModel("http://books", BookNoAnnotations.class, "classpath:/resources/model.xml", null);

BookNoAnnotations is either an interface or concrete class with no JAX-RS annotations. Both client proxies and server endpoints can 'turn' it into a RESTful resource by applying an external user model.

CXF WebClient API

HTTP centric clients are WebClient instances which also implement the Client interface. In addition to setting various Client request properties, you can also make an explicit HTTP invocation with an HTTP verb being the name of a given operation :

Code Block
java
java
WebClient client = WebClient.create("http://books");
Book book = client.path("bookstore/books").accept("text/xml").get(Book.class);

You can choose to get an explicit JAX-RS Response instead and check the response code, headers or entity body if any:

Code Block
java
java
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);

WebClient lets you get back to a base URI or to a previous path segment and move forward, it can be handy for getting a number of individual entries from a service with ids embedded in path segments HTTP centric clients are WebClient instances which also implement the Client interface. In addition to setting various Client request properties, you can also make an explicit HTTP invocation with an HTTP verb being the name of a given operation :

Code Block
java
java
WebClient client = WebClient.create("http://books");
BookList<Book> bookbooks = getBooks(client, 1L, 2L, 3L)

private List<Book> getBooks(WebClient client.path("bookstore/books").accept("text/xml").get(Book.class);

You can choose to get an explicit JAX-RS Response instead and check the response code, headers or entity body if any:

...

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);
, Long ...ids) {
   List<Book> books = new ArrayList<Book>(); 
   for (Long id : ids) {
       books.add(client.path(id).get(Book.class));
       client.back(); 
   } 
   return books;
}

The above code will send requests like "GET http://books/1", "GET http://books/2", etc.

If the request URI can be parameterized then you may want to use the following codeWebClient lets you get back to a base URI or to a previous path segment and move forward, it can be handy for getting a number of individual entries from a service with ids embedded in path segments :

Code Block
java
java
WebClientBook clientbook = WebClient.create("http://books");
List<Book> books = getBooks(client, 1L, 2L, 3L)

private List<Book> getBooks(WebClient client, Long ...ids) {
   List<Book> books = new ArrayList<Book>(); 
   for (Long id : ids) {
       books.add(client.path(id).get(Book.class));
       client.back(); 
   } 
   return books;
}

The above code will send requests like "GET http://books/1", "GET http://books/2", etc.

If the request URI can be parameterized then you may want to use the following code:

...

Book book = WebClient.create("http://books").path("{year}/{id}", 2010, 123).get(Book.class);
// as opposed to
// WebClient.create("http://books").path(2010).path(123).get(Book.class);
.path("{year}/{id}", 2010, 123).get(Book.class);
// as opposed to
// WebClient.create("http://books").path(2010).path(123).get(Book.class);

When reusing the same WebClient instance for multiple invocations, one may want to reset its state with the help of the reset() method, for example, when the Accept header value needs to be changed and the current URI needs to be reset to the baseURI (as an alternative to a back(true) call). The resetQuery() method may be used to reset the query values only. Both options are available for proxies too.

Anchor
asynchronousinvocations
asynchronousinvocations

Asynchronous invocations

WebClient has several methods accepting JAX-RS 2.0 InvocationCallback and returning Future. Alternatively, users can also use WebClient.async() shortcut to work with a standard AsyncInvoker.

Working with explicit collections

WebClient supports GenericEntity and JAX-RS 2.0 GenericType directly and via JAX-RS 2.0 SyncInvoker and AsyncInvoker to make it easier to work with the explicit collections.

WebClient also has few collection-aware methods, example:

Code Block
java
java
Collection<? extends Book> books = WebClient.getCollection(Book.class);
Collection<? extends Book> books = WebClient.postAndGetCollection(new ArrayList<Book>(), Book.class);

Handling exceptions

You can handle remote exceptions by either explicitly getting a Response object as shown above and handling error statuses as needed or you can catch either javax.ws.rs.WebApplicationException or javax.ws.rs.ProcessingException exceptions, the same way it can be done with proxies.

Configuring HTTP clients in Spring

Like proxies, HTTP clients can be created using a number of WebClient static utility methods: you can pass a location to a Spring configuration bean if needed or you can set up a default bus as shown above. For example:

Code Block
xml
xml
<bean id="myJsonProvider" class="org.apache.cxf.jaxrs.provider.JSONProvider" > 
    <property name="supportUnwrapped" value="true" /> 
    <property name="wrapperName" value="nodeName" /> 
</bean> 

<util:list id="webClientProviders"> 
    <ref bean="myJsonProvider"/> 
</util:list> 

<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> 

Note, starting from CXF 2.7.5 it is possible to set-up WebClient instances the same way as proxies, using jaxrs:client:

Code Block
xml
xml
<jaxrs:client id="webClient"
    address="https://localhost:${port}/services/rest"
    serviceClass

When reusing the same WebClient instance for multiple invocations, one may want to reset its state with the help of the reset() method, for example, when the Accept header value needs to be changed and the current URI needs to be reset to the baseURI (as an alternative to a back(true) call). The resetQuery() method may be used to reset the query values only. Both options are available for proxies too.

...

Asynchronous invocations

WebClient has several methods accepting JAX-RS 2.0 InvocationCallback and returning Future. Alternatively, users can also use WebClient.async() shortcut to work with a standard AsyncInvoker.

Working with explicit collections

WebClient supports GenericEntity and JAX-RS 2.0 GenericType directly and via JAX-RS 2.0 SyncInvoker and AsyncInvoker to make it easier to work with the explicit collections.

WebClient also has few collection-aware methods, example:

...

Collection<? extends Book> books = WebClient.getCollection(Book.class);
Collection<? extends Book> books = WebClient.postAndGetCollection(new ArrayList<Book>(), Book.class);

Handling exceptions

You can handle remote exceptions by either explicitly getting a Response object as shown above and handling error statuses as needed or you can catch either javax.ws.rs.WebApplicationException or javax.ws.rs.ProcessingException exceptions, the same way it can be done with proxies.

Configuring HTTP clients in Spring

Like proxies, HTTP clients can be created using a number of WebClient static utility methods: you can pass a location to a Spring configuration bean if needed or you can set up a default bus as shown above. For example:

Code Block
xmlxml
<bean id="myJsonProvider" 
class="org.apache.cxf.jaxrs.providerclient.JSONProviderWebClient" > 
        <property name="supportUnwrapped" value="true" /> <jaxrs:headers>
        <property<entry namekey="wrapperNameAccept" value="nodeNametext/xml" /> 
    </bean> 

<util:list id="webClientProviders"> 
    <ref bean="myJsonProvider"/> 
</util:list> 

<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> 

Note, starting from CXF 2.7.5 it is possible to set-up WebClient instances the same way as proxies, using jaxrs:client:

...

<jaxrs:client id="webClient"
         address="https://localhost:${port}/services/rest"
         serviceClass="org.apache.cxf.jaxrs.client.WebClient">
         <jaxrs:headers>
             <entry key="Accept" value="text/xml"/>
         </jaxrs:headers>
  </jaxrs:client>

The only limitation of using this option is that some of jaxrs:client attributes ("inheritHeaders", "modelRef") and elements ("model") are not really applicable to WebClient.

XML-centric clients

XML-centric clients are WebClients using an XMLSource utility class. XMLSource has a number of methods facilitating the retrieval of JAXB beans, individual properties or links with the help of XPath expressions. For example:

...

WebClient wc = WebClient.create("http://aggregated/data");
XMLSource source = wc.get(XMLSource.class);
source.setBuffering(true);
Book b1 = source.getNode("/books/book[position() = 1]", Book.class);
Book b2 = source.getNode("/books/book[position() = 2]", Book.class);
jaxrs:headers>
</jaxrs:client>

The only limitation of using this option is that some of jaxrs:client attributes ("inheritHeaders", "modelRef") and elements ("model") are not really applicable to WebClient.

XML-centric clients

XML-centric clients are WebClients using an XMLSource utility class. XMLSource has a number of methods facilitating the retrieval of JAXB beans, individual properties or links with the help of XPath expressions. For example:

Code Block
java
java
WebClient wc = WebClient.create("http://aggregated/data");
XMLSource source = wc.get(XMLSource.class);
source.setBuffering(true);
Book b1 = source.getNode("/books/book[position() = 1]", Book.class);
Book b2 = source.getNode("/books/book[position() = 2]", Book.class);

Note that an XMLSource instance can be set to buffer the input stream thus allowing for executing multiple XPath queries.
XMlSource can also help with getting the URIs representing the links or XML instances as Strings.

Support for arbitrary HTTP methods for sync invocations.

To get the arbitrary HTTP methods supported with the synchronous client calls or bypass some known Java HTTPUrlConnection issues (example it will block empty DELETE requests) add the HttpClient-based transport dependency and set a "use.async.http.conduit" contextual property.

This will work as is for asynchronous calls given that the HttpClient-based transport is required.

Thread Safety

Proxies and web clients (clients) are not thread safe by default. In some cases this can be a limitation, especially when clients are injected; synchronizing on them can cause performance side effects.

One way to 'make' clients thread-safe is to use WebClient.fromClient(Client) for web clients or JAXRSClientFactoryBean.fromClient() factory methods which copy all the original configuration properties and can be used to create new client instances per every request.

A single client doing multiple invocations without changing the current URI or headers is thread-safe (while creating a Invocation.Builder instances concurrently is not thread-safe since the shared instance of non-thread-safe class ClientProviderFactory is used under the hood). The only limitation in this case applies to proxies, in that they can not get "out of band" headers without synchronizing, ex :

Code Block
java
java
// get some response headers passed to us 'out of band', which is not thread-safe for a plain proxy: 
String bookHeader = WebClient.client(injectedBookStoreProxy).getHeaders().getFirst("BookHeader"); 

Final option is to use a 'threadSafe' boolean property when creating proxies or web clients (either from Spring or programmatically), see this test for more details. Thread-safe clients created this way keep their state in a thread-local storage.

If a number of incoming threads is limited then one option is just do nothing, while the other option is to reset the thread local state :

Code Block
java
java
try { 
   webClient.path("bar") 
   webClient.header("bar", baz); 
   webClient.invoke(...); 
} finally { 
   // if using a proxy: WebClient.client(proxy).reset(); 
   webClient.reset(); 
} 

Yet another option is to use JAXRSClientFactoryBean and a 'secondsToKeepState' property for creating thread-safe clients - this will instruct clients to clean-up the thread-local state periodically.

Configuring Clients at Runtime

Proxy and http-centric clients are typically created by JAXRSClientFactory or WebClient factory methods but JAXRSClientFactoryBean can also be used for pre-configuring clients before they are created.

Sometimes, you may want to configure a client instance after it is been created. For example, one may want to configure HTTPConduit programmatically, as opposed to setting its properties using Spring. ClientConfiguration represents a client-specific configuration state and can be accessed like this :

Code Block
java
java
Book proxy = JAXRSClientFactory.create("http://books", Book.class);
ClientConfiguration config = WebClient.getConfig(proxy);
HTTPConduit conduit1 = (HTTPConduit)config.getConduit();

WebClient webclient = WebClient.create("http://books");
HTTPConduit conduit2 = (HTTPConduit)WebClient.getConfig(webclient).getConduit();

When working with JAX-RS 2.0 Client API one can set some low-level HTTP properties via Configurable interface:

Code Block
java
java
//http.connection.timeout
//http.receive.timeout
//http.proxy.server.uri
//http.proxy.server.port
Client client = ClientBuilder.newClient();
client.property("http.receive.timeout", 1000000); 

Creating clients programmatically with no Spring dependencies

Example :

Code Block
java
java
JAXRSClientFactoryBean sf = new JAXRSClientFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setAddress("http://localhost:9000/");
BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = new JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
CustomerService service = sf.create(CustomerService.class);
WebClient wc = sf.createWebClient();

Configuring an HTTP Conduit from Spring

There's a number of ways to configure HTTPConduits for proxies and WebClients.

It is possible to have an HTTPConduit configuration which will apply to all clients using different request URIs or only to those with using a specific URI. For example:

Code Block
xml
xml
<http:conduit name="http://books:9095/bookstore.*"/> 

This configuration will affect all proxies and WebClients which have requestURIs starting from 'http://books:9095/bookstore'. Note the trailing '.*' suffix in the name of the http:conduit element.

Please see this configuration file for more examples.

Alternatively you can just do:

Code Block
xml
xml
<http:conduit name="*.http-conduit"/> 

This configuration will affect all the clients, irrespective of the URIs being dealt with.

If you work with proxies then you can have the proxy-specific configuration using the expanded QName notation

Note that an XMLSource instance can be set to buffer the input stream thus allowing for executing multiple XPath queries.
XMlSource can also help with getting the URIs representing the links or XML instances as Strings.

Support for arbitrary HTTP methods for sync invocations.

To get the arbitrary HTTP methods supported with the synchronous client calls or bypass some known Java HTTPUrlConnection issues (example it will block empty DELETE requests) add the HttpClient-based transport dependency and set a "use.async.http.conduit" contextual property.

This will work as is for asynchronous calls given that the HttpClient-based transport is required.

Thread Safety

Proxies and web clients (clients) are not thread safe by default. In some cases this can be a limitation, especially when clients are injected; synchronizing on them can cause performance side effects.

One way to 'make' clients thread-safe is to use WebClient.fromClient(Client) for web clients or JAXRSClientFactoryBean.fromClient() factory methods which copy all the original configuration properties and can be used to create new client instances per every request.

A single client doing multiple invocations without changing the current URI or headers is thread-safe. The only limitation in this case applies to proxies, in that they can not get "out of band" headers without synchronizing, ex :

...

// get some response headers passed to us 'out of band', which is not thread-safe for a plain proxy: 
String bookHeader = WebClient.toClient(injectedBookStoreProxy).getHeaders().getFirst("BookHeader"); 

Final option is to use a 'threadSafe' boolean property when creating proxies or web clients (either from Spring or programmatically), see this test for more details. Thread-safe clients created this way keep their state in a thread-local storage.

If a number of incoming threads is limited then one option is just do nothing, while the other option is to reset the thread local state :

...

try { 
   webClient.path("bar") 
   webClient.header("bar", baz); 
   webClient.invoke(...); 
} finally { 
   // if using a proxy: WebClient.client(proxy).reset(); 
   webClient.reset(); 
} 

Yet another option is to use JAXRSClientFactoryBean and a 'secondsToKeepState' property for creating thread-safe clients - this will instruct clients to clean-up the thread-local state periodically.

Configuring Clients at Runtime

Proxy and http-centric clients are typically created by JAXRSClientFactory or WebClient factory methods but JAXRSClientFactoryBean can also be used for pre-configuring clients before they are created.

Sometimes, you may want to configure a client instance after it is been created. For example, one may want to configure HTTPConduit programmatically, as opposed to setting its properties using Spring. ClientConfiguration represents a client-specific configuration state and can be accessed like this :

...

Book proxy = JAXRSClientFactory.create("http://books", Book.class);
ClientConfiguration config = WebClient.getConfig(proxy);
HTTPConduit conduit1 = (HTTPConduit)config.getConduit();

WebClient webclient = WebClient.create("http://books");
HTTPConduit conduit2 = (HTTPConduit)WebClient.getConfig(webclient).getConduit();

Creating clients programmatically with no Spring dependencies

Example :

...

JAXRSClientFactoryBean sf = new JAXRSClientFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setAddress("http://localhost:9000/");
BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = new JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
CustomerService service = sf.create(CustomerService.class);
WebClient wc = sf.createWebClient();

Configuring an HTTP Conduit from Spring

There's a number of ways to configure HTTPConduits for proxies and WebClients.

It is possible to have an HTTPConduit configuration which will apply to all clients using different request URIs or only to those with using a specific URI. For example:

Code Block
xml
xml
<http:conduit name="{http://books:9095/bookstore.*foo.bar}BookService.http-conduit"/> 

This configuration will affect all proxies and WebClients which have requestURIs starting from 'http://books:9095/bookstore'. Note the trailing '.*' suffix in the name of the http:conduit element.

Please see this configuration file for more examples.

In this example, 'foo.bar' is a reverse package name of the BookService proxy class.

Similarly, for WebClients you can Alternatively you can just do:

Code Block
xml
xml
<http:conduit name="*{http://localhost:8080}WebClient.http-conduit"/> 

This configuration will affect all the clients, irrespective of the URIs being dealt with.

If you work with proxies then you can have the proxy-specific configuration using the expanded QName notation:

...

<http:conduit name="{http://foo.bar}BookService.http-conduit"/> 

In this example, 'foo.bar' is a reverse package name of the BookService proxy class.

Similarly, for WebClients you can do:

...

<http:conduit name="{http://localhost:8080}WebClient.http-conduit"/> 

In this example, 'http://localhost:8080' is the base service URI.

Please see jaxrs-https-client1.xml and jaxrs-https-client2.xml configuration files for more examples.

Also see this wiki page on how to configure HTTPConduits.

Clients and Authentication

Proxies and HTTP-centric clients can have the HTTP Authorization header set up explicitly:

Code Block
java
java
// Replace 'user' and 'password' by the actual values
String authorizationHeader = "Basic " 
    + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());

// proxies
WebClient.client(proxy).header("Authorization", authorizationHeader);

// web clients
webClient.header("Authorization", authorizationHeader);

or by providing a username and password pair at client creation time, for example

In this example, 'http://localhost:8080' is the base service URI.

Please see jaxrs-https-client1.xml and jaxrs-https-client2.xml configuration files for more examples.

Also see this wiki page on how to configure HTTPConduits.

Clients and Authentication

Proxies and HTTP-centric clients can have the HTTP Authorization header set up explicitly:

Code Block
java
java
BookStore proxy = JAXRSClientFactory.create("http:// Replace 'user' and 'password' by the actual values
String authorizationHeader = "Basic " 
    + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());

// proxies
WebClient.client(proxy).header("Authorization", authorizationHeader);

// web clients
webClient.header("Authorization", authorizationHeader);

or by providing a username and password pair at client creation time, for example:

...

BookStore proxy = JAXRSClientFactory.create("http://books", BookStore.class, "username", "password", "classpath:/config/https.xml");

WebClient client = WebClient.create("http://books", "username", "password", "classpath:/config/https.xml");
books", BookStore.class, "username", "password", "classpath:/config/https.xml");

WebClient client = WebClient.create("http://books", "username", "password", "classpath:/config/https.xml");

When injecting clients from Spring, one can add 'username' and 'password' values as attributes to jaxrs:client elements or add them to WebClient factory create methods.

Clients in Spring Boot

Please see JAXRSClientSpringBoot documentation on how CXF JAX-RS Clients can be used in a SpringBoot Application.

Clients and HTTP(s)

The default HttpClientHTTPConduit conduit by default supports the following HTTPS protocols: TLSv1, TLSv1.1, TLSv1.2, TLSv1.3. Since Apache CXF 4.0.4 / 3.6.3 release, the default HttpClientHTTPConduit respects https.protocols system property (see please https://blogs.oracle.com/java/post/diagnosing-tls-ssl-and-https) and if set, would use the provided protocols. This behavior could be turned off by setting https.protocols.ignored system property to "true" (the default value is "false")When injecting clients from Spring, one can add 'username' and 'password' values as attributes to jaxrs:client elements or add them to WebClient factory create methods.