Contents

Overview

WebClient is an HTTP client of Helidon SE. It handles the responses to the HTTP requests in a reactive way.

Helidon WebClient provides the following features:

  • Reactive approach
    Allows you to execute HTTP requests and handle the responses without having to wait for the server response. When the response is received, the client requests only the amount of data that it can handle at that time. So, there is no overflow of memory.

  • Builder-like setup and execution
    Creates every client and request as a builder pattern. This improves readability and code maintenance.

  • Redirect chain
    Follows the redirect chain and perform requests on the correct endpoint by itself.

  • Tracing and security propagation
    Automatically propagates the configured tracing and security settings of the Helidon WebServer to the WebClient and uses them during request and response.

Maven Coordinates

To enable WebClient add the following dependency to your project’s pom.xml (see Managing Dependencies).

<dependency>
    <groupId>io.helidon.webclient</groupId>
    <artifactId>helidon-webclient</artifactId>
</dependency>
Copied

Usage

Creating the WebClient

You can create WebClient by executing WebClient.create() method. This will create an instance of client with default settings and without a base uri set.

To change the default settings and register additional services, you can use simple builder that allows you to customize the client behavior.

Create a WebClient with simple builder:
WebClient client = WebClient.builder()
        .baseUri("http://localhost")
        .build();
Copied

Creating and Executing the WebClient Request

WebClient executes requests to the target endpoints and returns specific response type.

It offers variety of methods to specify the type of request you want to execute:

  • put()

  • get()

  • method(String methodName)

These methods set specific request type based on their name or parameter to the new instance of WebClientRequesBuilder and return this instance based on configurations for specific request type.

You can set configuration for every request type before it is sent as described in .

For the final execution, use the following methods with variations and different parameters:

  • Single<T> submit(Object entity, Class<T> responseType)

  • Single<T> request(Class<T> responseType)

Execute a simple GET request to endpoint:
Single<String> response = client.get()
        .path("/endpoint")
        .request(String.class);
Copied

Configuring the WebClient

The class responsible for WebClient configuration is:

Configuration of the HTTP client

Type: io.helidon.webclient.WebClientConfiguration

This is a standalone configuration type, prefix from configuration root: client

Configuration options

Optional configuration options
keytypedefault valuedescription
connect-timeout-millis

long

60000

Sets new connection timeout of the request.

cookies.automatic-store-enabled

boolean

 

Whether to allow automatic cookie storing

cookies.default-cookies

Map

 

Default cookies to be used in each request. Each list entry has to have "name" and "value" node

dns-resolver-type

DnsResolverType (DEFAULT, ROUND_ROBIN, NONE)

 

Set which type of DNS resolver should be used.

follow-redirects

boolean

false

Whether to follow any response redirections or not.

headers

Map

 

Default headers to be used in each request. Each list entry has to have "name" and "value" node

keep-alive

boolean

true

Enable keep alive option on the connection.

max-redirects

int

5

Sets max number of followed redirects.

media-support 
proxy 

Sets new request proxy.

read-timeout-millis

long

600000

Sets new read timeout of the response.

relative-uris

boolean

false

Can be set to true to force the use of relative URIs in all requests, regardless of the presence or absence of proxies or no-proxy lists.

tls 

New TLS configuration.

uri

string

 

Base URI for each request

user-agent

string

 

Name of the user agent which should be used.

Example of a WebClient Runtime Configuration

Config config = Config.create();
WebClient client = WebClient.builder()
        .baseUri("http://localhost")
        .config(config.get("client"))
        .build();
Copied

Example of a WebClient YAML Configuration

client:
  connect-timeout-millis: 2000
  read-timeout-millis: 2000
  follow-redirects: true 
  max-redirects: 5
  cookies:
    automatic-store-enabled: true
    default-cookies:
      - name: "env"
        value: "dev"
  headers:
    - name: "Accept"
      value: ["application/json","text/plain"] 
  services: 
    config:
      metrics:
        - methods: ["PUT", "POST", "DELETE"]
        - type: METER
          name-format: "client.meter.overall"
        - type: TIMER
          # meter per method
          name-format: "client.meter.%1$s"
        - methods: ["GET"]
          type: COUNTER
          errors: false
          name-format: "client.counter.%1$s.success"
          description: "Counter of successful GET requests"
        - methods: ["PUT", "POST", "DELETE"]
          type: COUNTER
          success: false
          name-format: "wc.counter.%1$s.error"
          description: "Counter of failed PUT, POST and DELETE requests"
        - methods: ["GET"]
          type: GAUGE_IN_PROGRESS
          name-format: "client.inprogress.%2$s"
          description: "In progress requests to host"
      tracing:
  proxy: 
    use-system-selector: false
    host: "hostName"
    port: 80
    no-proxy: ["localhost:8080", ".helidon.io", "192.168.1.1"]
  tls: 
    server:
      trust-all: true
      disable-hostname-verification: true
      keystore:
        passphrase: "password"
        trust-store: true
        resource:
          resource-path: "client.p12"
    client:
      keystore:
        passphrase: "password"
        resource:
          resource-path: "client.p12"
Copied
  • Client functional settings
  • Default client headers and cookies
  • Client service configuration
  • Proxy configuration
  • TLS configuration

Examples

Request Configuration

The request settings are based on the following optional parameters, and change when a specific request is executed.

ParameterDescription
uri("http://example.com")Overrides baseUri from WebClient
path("/path")Adds path to the uri
queryParam("query", "parameter")Adds query parameter to the request
fragment("someFragment")Adds fragment to the request
headers(headers → headers.addAccept(MediaType.APPLICATION_JSON))Adds header to the request

WebClientRequestBuilder class also provides specific header methods that help the user to set a particular header. The methods are:

  • contentType (MediaType contentType)

  • accept (MediaType…​ mediaTypes)

For more details, see the Request Headers API.

Adding JSON Processing Media Support to the WebClient

JSON Processing (JSON-P) media support is not present in the WebClient by default. So, in this case, you must first register it before making a request. This example shows how to register JsonpSupport using the following two methods.

Register JSON-P support to the WebClient.
WebClient.builder()
        .baseUri("http://localhost")
        .addReader(JsonpSupport.reader()) 
        .addWriter(JsonpSupport.writer()) 
        .addMediaService(JsonpSupport.create()) 
        .build();
Copied
  • Adds JSON-P reader to all client requests.
  • Adds JSON-P writer to all client requests.
  • Adds JSON-P writer and reader to all client requests.
Register JSON-P support only to the specific request.
WebClient webClient = WebClient.create();

WebClientRequestBuilder requestBuilder = webClient.get();
requestBuilder.writerContext().registerWriter(JsonSupport.writer()); 
requestBuilder.readerContext().registerReader(JsonSupport.reader()); 

requestBuilder.request(JsonObject.class)
Copied
  • Adds JSON-P writer only to this request.
  • Adds JSON-P reader only to this request.

WebClient TLS setup

Configure TLS either programmatically or by the Helidon configuration framework.

Configuring TLS in your code

One way to configure TLS in WebClient is in your application code as shown below.

KeyConfig keyConfig = KeyConfig.keystoreBuilder()
                //Whether this keystore is also trust store
                .trustStore()
                //Keystore location/name
                .keystore(Resource.create("client.p12"))
                //Password to the keystore
                .keystorePassphrase("password")
                .build();

WebClient.builder()
         .tls(WebClientTls.builder()
               .certificateTrustStore(keyConfig)
               .clientKeyStore(keyConfig)
               .build())
         .build();
Copied

Configuring TLS in the config file

Another way to configure TLS in WebClient is through the application.yaml configuration file.

WebClient TLS configuration file application.yaml
webclient:
  tls:
    #Server part defines settings for server certificate validation and truststore
    server:
      keystore:
        passphrase: "password"
        trust-store: true
        resource:
          resource-path: "keystore.p12"
    #Client part defines access to the keystore with client private key or certificate
    client:
      keystore:
        passphrase: "password"
        resource:
          resource-path: "keystore.p12"
Copied

Then, in your application code, load the configuration from that file.

WebClient initialization using the application.yaml file located on the classpath
Config config = Config.create();
WebClient webClient = WebClient.create(config.get("webclient"));
Copied

Or you can only create WebClientTls instance based on the config file.

WebClientTls instance based on application.yaml file located on the classpath
Config config = Config.create();
WebClientTls.builder()
    .config(config.get("webclient.tls"))
    .build();
Copied

Reference