Choosing Connector in Jersey

Jersey is using JDK HttpUrlConnection for sending HTTP requests by default. However, there are cases where the default HttpUrlConnection cannot be used, or where using any other HTTP Client available suits the customer’s needs better.

For this, Jersey comes with a Connector. The Connector SPI is a bridge between Jakarta REST Client API and a third-party HTTP Client performing the HTTP request. There are multiple ways to choose another Connector:

1. The most common way is to register the ConnectorProvider in the ClientConfig:

ClientConfig clientConfig = new ClientConfig();
clientConfig.connectorProvider(new XXXConnectorProvider());
Client client = ClientBuilder.newBuilder().withConfig(clientConfig).build();

2. In Microprofile RestClient, the connector can be registered as follows:

RestClientBuilder.newBuilder()
                .baseUri(...)
                .register(XXXConnectorProvider.class)
                .build(...);

3. To automatically register the connector to every Client, the JDK service can be used. The provider-configuration file

META-INF/services/org.glassfish.jersey.client.spi.ConnectorProvider

needs to contain the fully-qualified binary name of the concrete connector provider class.

4. Using the CONNECTOR_PROVIDER property. The property needs to be applied on ClientBuilder, or ClientConfig, otherwise, the property is ignored:

Client client = ClientBuilder.newBuilder()
  .property(ClientProperties.CONNECTOR_PROVIDER, XXXConnectorProvider.class.getName())
  .build();

The advantage of having a property is the ability to use the property for instance in a MicroProfile Config configuration file.

Why choose the connector

There are multiple reasons to use different connectors. One example where the HttpUrlConnection cannot be used is the HTTP PATCH request. The HttpUrlConnection does not support the HTTP PATCH method. Jersey provides the option to add HTTP PATCH to the list of HttpUrlConnection’s known methods using reflection by setting the property HttpUrlConnectorProvider.SET_METHOD_WORKAROUND=true. However, since JDK 16, it is no longer possible to use reflection on classes from JDK.

Other reasons can be connection pooling, HTTP/2 support, or other features provided by the respective HTTP Client.

Warning

Some connectors cannot support the Jersey multipart feature. This is because multipart updates the HTTP content-type header when the entity is processed, but the third-party HTTP client may wire the HTTP headers before the entity is processed, and the content-type header change is not reflected by the third-party client.

This entry was posted in Jersey. Bookmark the permalink.