Class RestClient.Builder<SELF extends RestClient.Builder<SELF>>

java.lang.Object
org.apache.juneau.marshall.Context.Builder<SELF>
org.apache.juneau.marshall.MarshallingContextable.Builder<SELF>
org.apache.juneau.rest.client.classic.RestClient.Builder<SELF>
Direct Known Subclasses:
MockRestClient.Builder, RestClient.DefaultBuilder
Enclosing class:
RestClient

public abstract static class RestClient.Builder<SELF extends RestClient.Builder<SELF>> extends MarshallingContextable.Builder<SELF>
Builder class.
  • Constructor Details

    • Builder

      protected Builder()
      Constructor.
  • Method Details

    • accept

      public SELF accept(String value)
      Appends an Accept header on this request.

      This is a shortcut for calling headerData().append(Accept.of(value)).

      Parameters:
      value - The new header value.
      Can be null (no Accept header will be added).
      Returns:
      This object.
      See Also:
    • acceptCharset

      public SELF acceptCharset(String value)
      Sets the value for the Accept-Charset request header on all requests.

      This is a shortcut for calling headerData().append(AcceptCharset.of(value)).

      Parameters:
      value - The new header value.
      Can be null (no Accept-Charset header will be added).
      Returns:
      This object.
      See Also:
    • addBeanTypes

      public SELF addBeanTypes()
      Serializer configuration property:  Add "_type" properties when needed.

      When enabled, "_type" properties will be added to beans if their type cannot be inferred through reflection.

      This is used to recreate the correct objects during parsing if the object types cannot be inferred.
      For example, when serializing a Map<String,Object> field where the bean class cannot be determined from the type of the values.

      Note the differences between the following settings:

      Example:

      // Create a JSON client that adds _type to nodes in the request body. RestClient client = RestClient .create() .json() .addBeanTypes() .build(); // Our map of beans to serialize. @Marshalled(typeName="mybean") public class MyBean { public String foo = "bar"; } AMap map = AMap.of("foo", new MyBean()); // Request body will contain: {"foo":{"_type":"mybean","foo":"bar"}} client .post("http://localhost:10000/foo", map) .run();

      See Also:
      Returns:
      This object.
    • addInterceptorFirst

      Adds this protocol interceptor to the head of the protocol processing list.
      Notes:
      Parameters:
      itcp - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • addInterceptorFirst

      Adds this protocol interceptor to the head of the protocol processing list.
      Notes:
      Parameters:
      itcp - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • addInterceptorLast

      Adds this protocol interceptor to the tail of the protocol processing list.
      Notes:
      Parameters:
      itcp - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • addInterceptorLast

      Adds this protocol interceptor to the tail of the protocol processing list.
      Notes:
      Parameters:
      itcp - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • addRootType

      public SELF addRootType()
      Serializer configuration property:  Add type attribute to root nodes.

      When enabled, "_type" properties will be added to top-level beans.

      When disabled, it is assumed that the parser knows the exact Java POJO type being parsed, and therefore top-level type information that might normally be included to determine the data type will not be serialized.

      For example, when serializing a top-level POJO with a @Marshalled(typeName) value, a '_type' attribute will only be added when this setting is enabled.

      Note the differences between the following settings:

      Example:

      // Create a JSON client that adds _type to root node. RestClient client = RestClient .create() .json() .addRootType() .build(); // Our bean to serialize. @Marshalled(typeName="mybean") public class MyBean { public String foo = "bar"; } // Request body will contain: {"_type":"mybean","foo":"bar"} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • backoffManager

      public SELF backoffManager(BackoffManager backoffManager)
      Assigns BackoffManager instance.
      Parameters:
      backoffManager - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • basicAuth

      public SELF basicAuth(String host, int port, String user, String pw)
      Set up this client to use BASIC auth.
      Example:

      // Construct a client that uses BASIC authentication. RestClient client = RestClient .create() .basicAuth("http://localhost", 80, "me", "mypassword") .build();

      Parameters:
      host - The auth scope hostname.
      Can be null (will use "*" as the hostname).
      port - The auth scope port.
      user - The username.
      Can be null (will use empty string).
      pw - The password.
      Can be null (will use empty string).
      Returns:
      This object.
    • build

      public RestClient build()
      Description copied from class: Context.Builder
      Build the object.
      Overrides:
      build in class Context.Builder<SELF extends RestClient.Builder<SELF>>
      Returns:
      The built object.
    • callHandler

      Returns the creator for the rest call handler.

      Allows you to provide a custom handler for making HTTP calls.

      Example:

      // Create a client that handles processing of requests using a custom handler. public class MyRestCallHandler implements RestCallHandler { @Override public HttpResponse run(HttpHost target, HttpRequest request, HttpContext context) throws IOException { // Custom handle requests. } } RestClient client = RestClient .create() .callHandler(MyRestCallHandler.class) .build();

      Notes:
      • The SSRF guard of @Remote calls travels on the request's HttpContext, and a custom handler may copy the request, or send it with another context, without it. So a client with any handler other than BasicRestCallHandler itself, or with a BasicRestCallHandler bound to a different client (through impl(...)), refuses every SSRF-guard-active @Remote call (one without the allowPrivateUrls opt-in). Ordinary requests are unaffected.
      • The RestClient.run(HttpHost, HttpRequest, HttpContext) method can also be overridden to produce the same results. The same SSRF restriction applies: a client whose class overrides that method or either execute(...) overload it dispatches to refuses SSRF-guard-active @Remote calls too.
      • Use BeanInstantiator.Builder impl(Object) to specify an already instantiated instance.
      • Use BeanInstantiator.Builder type(Class) to specify a subtype to instantiate.
        Subclass must have a public constructor that takes in any args available in the bean store of this builder (including RestClient itself).
      See Also:
      Returns:
      The instantiator for the rest call handler.
    • callHandler

      public SELF callHandler(Class<? extends RestCallHandler> value)
      REST call handler class.

      Specifies a custom handler for making HTTP calls.

      This is a shortcut for callHandler().type(value).

      Parameters:
      value - The new value for this setting.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • clientVersion

      public SELF clientVersion(String value)
      Sets the client version by setting the value for the "Client-Version" header.

      This is a shortcut for calling headerData().append(ClientVersion.of(value)).

      Parameters:
      value - The version string (e.g. "1.2.3")
      Can be null (no Client-Version header will be added).
      Returns:
      This object.
      See Also:
    • connectionBackoffStrategy

      public SELF connectionBackoffStrategy(ConnectionBackoffStrategy connectionBackoffStrategy)
      Assigns ConnectionBackoffStrategy instance.
      Parameters:
      connectionBackoffStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • connectionManager

      Assigns HttpClientConnectionManager instance.
      Notes:
      • This client cannot pin the connections of a connection manager it did not create, so a client built with one refuses every SSRF-guard-active @Remote call (one without the allowPrivateUrls opt-in). Ordinary requests are unaffected.
      Parameters:
      value - New property value.
      Can be null (value will not be set, a default connection manager will be created).
      Returns:
      This object.
      See Also:
    • connectionManagerShared

      public SELF connectionManagerShared(boolean shared)
      Defines the connection manager is to be shared by multiple client instances.
      Notes:
      • If the connection manager is shared its life-cycle is expected to be managed by the caller and it will not be shut down if the client is closed. This applies to a connection manager supplied through connectionManager(HttpClientConnectionManager) or returned by an overridden createConnectionManager() (even one that calls super, since the override may hand the same instance to several clients). The connection manager the default createConnectionManager() builds for a client cannot be reached by the caller, so it is never shared: RestClient.close() shuts it down.
      • The client's internal pool for SSRF-guard-active @Remote calls (see createConnectionManager()) is never shared, and RestClient.close() still shuts it down. Combined with keepHttpClientOpen(), though, nothing shuts that internal pool (or the default connection manager) down; their connections stay open until they are closed as idle or the JVM exits.
      Parameters:
      shared - New property value.
      Returns:
      This object.
      See Also:
    • connectionReuseStrategy

      Assigns ConnectionReuseStrategy instance.
      Parameters:
      reuseStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • connectionTimeToLive

      public SELF connectionTimeToLive(long connTimeToLive, TimeUnit connTimeToLiveTimeUnit)
      Sets maximum time to live for persistent connections.
      Notes:
      Parameters:
      connTimeToLive - New property value.
      connTimeToLiveTimeUnit - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • console

      public SELF console(PrintStream value)
      Console print stream

      Allows you to redirect the console output to a different print stream.

      Parameters:
      value - The new value for this setting.
      Can be null (defaults to System.err).
      Returns:
      This object.
    • contentDecoderRegistry

      Assigns a map of InputStreamFactories to be used for automatic content decompression.
      Parameters:
      contentDecoderMap - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • contentType

      public SELF contentType(String value)
      Sets the value for the Content-Type request header on all requests.

      This is a shortcut for calling headerData().append(ContentType.of(value)).

      This overrides the media type specified on the serializer.

      Parameters:
      value - The new header value.
      Can be null (no Content-Type header will be added).
      Returns:
      This object.
      See Also:
    • copy

      public SELF copy()
      Description copied from class: Context.Builder
      Copy creator.
      Specified by:
      copy in class MarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>
      Returns:
      A new mutable copy of this builder.
    • debug

      public SELF debug()
      Sets the value for the Debug request header on all requests.

      This is a shortcut for calling headerData().append(Debug.of(value)).

      Overrides:
      debug in class MarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>
      Returns:
      This object.
      See Also:
    • debugOutputLines

      public SELF debugOutputLines(int value)
      Parser configuration property:  Debug output lines.

      When parse errors occur, this specifies the number of lines of input before and after the error location to be printed as part of the exception message.

      Example:

      // Create a parser whose exceptions print out 100 lines before and after the parse error location. RestClient client = RestClient .create() .json() .debug() // Enable debug mode to capture Reader contents as strings. .debugOuputLines(100) .build(); // Try to parse some bad JSON. try { client .get("/pathToBadJson") .run() .getContent().as(Object.class); // Try to parse it. } catch (RestCallException e) { System.err.println(e.getMessage()); // Will display 200 lines of the output. }

      See Also:
      Parameters:
      value - The new value for this property.
      The default value is 5.
      Returns:
      This object.
    • defaultAuthSchemeRegistry

      Assigns default AuthScheme registry which will be used for request execution if not explicitly set in the client execution context.
      Parameters:
      authSchemeRegistry - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultConnectionConfig

      Assigns default ConnectionConfig.
      Notes:
      Parameters:
      config - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultCookieSpecRegistry

      Assigns default CookieSpec registry which will be used for request execution if not explicitly set in the client execution context.
      Parameters:
      cookieSpecRegistry - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultCookieStore

      public SELF defaultCookieStore(CookieStore cookieStore)
      Assigns default CookieStore instance which will be used for request execution if not explicitly set in the client execution context.
      Parameters:
      cookieStore - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultCredentialsProvider

      public SELF defaultCredentialsProvider(CredentialsProvider credentialsProvider)
      Assigns default CredentialsProvider instance which will be used for request execution if not explicitly set in the client execution context.
      Parameters:
      credentialsProvider - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultRequestConfig

      Assigns default RequestConfig instance which will be used for request execution if not explicitly set in the client execution context.
      Parameters:
      config - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • defaultSocketConfig

      Assigns default SocketConfig.
      Notes:
      Parameters:
      config - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • detectLeaks

      public SELF detectLeaks()
      RestClient configuration property:  Enable leak detection.

      Enable client and request/response leak detection.

      Causes messages to be logged to the console if clients or request/response objects are not properly closed when the finalize methods are invoked.

      Automatically enabled with Context.Builder#debug().

      Example:

      // Create a client that logs a message if RestClient client = RestClient .create() .detectLeaks() .logToConsole() // Also log the error message to System.err .build(); client.closeQuietly(); // Customized HttpClient won't be closed.

      Returns:
      This object.
    • allowPrivateUrls

      public SELF allowPrivateUrls(boolean value)
      Opts every @Remote/@Url call made through this client out of the default deny-private SSRF guardrail (see org.apache.juneau.http.remote.RemoteUrlPolicy), for local-dev/intranet targets that are intentionally private.

      The effective per-call value is the logical OR of this setting, the RestClient.allowPrivateUrls system property, and the @Remote/@RemoteOp allowPrivateUrls annotation attribute: any one of the three opting in is sufficient. The http/ https scheme requirement is unaffected.

      Parameters:
      value - true to allow private/loopback/link-local/metadata @Remote targets. Default false.
      Returns:
      This object.
    • allowAddressRanges

      public SELF allowAddressRanges(String... value)
      Allows this client's SSRF-guarded @Remote/@Url calls to reach hosts inside the given special-purpose address ranges that the default policy denies (see org.apache.juneau.http.remote.RemoteUrlPolicy).

      Same narrow semantics and validation as the JVM-wide RestClient.allowAddressRanges system property: each entry is a CIDR range or single address (parsed without DNS) that must lie inside 192.0.0.0/24, 198.18.0.0/15, 224.0.0.0/4, 240.0.0.0/4 or ff00::/8. It never re-opens loopback, link-local/cloud-metadata, private, unspecified or any other deny.

      The effective allow-list is the union of this setting and the system property. Repeated calls accumulate. An invalid entry fails build() with an IllegalArgumentException.

      Parameters:
      value - The CIDR ranges or addresses to allow. Can be null or empty (no effect).
      Returns:
      This object.
    • detectRecursions

      BeanTraverse configuration property:  Automatically detect POJO recursions.

      When enabled, specifies that recursions should be checked for during traversal.

      Recursions can occur when traversing models that aren't true trees but rather contain loops.
      In general, unchecked recursions cause stack-overflow-errors.
      These show up as MarshallingRecursionException with the message "Depth too deep. Stack overflow occurred.".

      Notes:
      • Checking for recursion can cause a small performance penalty.
      Example:

      // Create a JSON client that automatically checks for recursions. RestClient client = RestClient .create() .json() .detectRecursions() .build(); // Create a POJO model with a recursive loop. public class A { public Object f; } A a = new A(); a.f = a; try { // Throws a RestCallException with an inner SerializeException and not a StackOverflowError client .post("http://localhost:10000/foo", a) .run(); } catch (RestCallException e} { // Handle exception. }

      See Also:
      Returns:
      This object.
    • disableAuthCaching

      Disables authentication scheme caching.
      Notes:
      Returns:
      This object.
      See Also:
    • disableAutomaticRetries

      Disables automatic request recovery and re-execution.
      Returns:
      This object.
      See Also:
    • disableConnectionState

      Disables connection state tracking.
      Returns:
      This object.
      See Also:
    • disableContentCompression

      Disables automatic content decompression.
      Notes:
      Returns:
      This object.
      See Also:
    • disableCookieManagement

      Disables state (cookie) management.
      Notes:
      Returns:
      This object.
      See Also:
    • disableRedirectHandling

      Disables automatic redirect handling.
      Returns:
      This object.
      See Also:
    • errorCodes

      public SELF errorCodes(Predicate<Integer> value)
      Errors codes predicate.

      Defines a predicate to test for error codes.

      Example:

      // Create a client that considers any 300+ responses to be errors. RestClient client = RestClient .create() .errorCodes(x -> x>=300) .build();

      Parameters:
      value - The new value for this setting.
      The default value is x -> x >= 400.
      Cannot be null.
      Returns:
      This object.
    • evictExpiredConnections

      Makes this instance of HttpClient proactively evict expired connections from the connection pool using a background thread.
      Notes:
      • One MUST explicitly close HttpClient with Closeable.close() in order to stop and release the background thread.
      • This method has no effect if the instance of HttpClient is configured to use a shared connection manager.
      • This method may not be used when the instance of HttpClient is created inside an EJB container.
      Returns:
      This object.
      See Also:
    • evictIdleConnections

      public SELF evictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUnit)
      Makes this instance of HttpClient proactively evict idle connections from the connection pool using a background thread.
      Notes:
      • One MUST explicitly close HttpClient with Closeable.close() in order to stop and release the background thread.
      • This method has no effect if the instance of HttpClient is configured to use a shared connection manager.
      • This method may not be used when the instance of HttpClient is created inside an EJB container.
      Parameters:
      maxIdleTime - New property value.
      maxIdleTimeUnit - New property value.
      Cannot be null.
      Returns:
      This object.
      See Also:
    • executorService

      public SELF executorService(ExecutorService executorService, boolean shutdownOnClose)
      RestClient configuration property:  Executor service.

      Defines the executor service to use when calling future methods on the RestRequest class.

      This executor service is used to create Future objects on the following methods:

      The default executor service is a single-threaded ThreadPoolExecutor with a 30 second timeout and a queue size of 10.

      Example:

      // Create a client with a customized executor service. RestClient client = RestClient .create() .executorService(new ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)), true) .build(); // Use it to asynchronously run a request. Future<RestResponse> responseFuture = client.get(URI).runFuture(); // Do some other stuff. // Now read the response. String body = responseFuture.get().getContent().asString(); // Use it to asynchronously retrieve a response. Future<MyBean> myBeanFuture = client .get(URI) .run() .getContent().asFuture(MyBean.class); // Do some other stuff. // Now read the response. MyBean bean = myBeanFuture.get();

      Parameters:
      executorService - The executor service.
      Can be null (a default executor service will be created if needed).
      shutdownOnClose - Call ExecutorService.shutdown() when RestClient.close() is called.
      Returns:
      This object.
    • formData

      public final PartList formData()
      Returns the builder for the list of form data parameters that get applied to all requests created by this builder.

      This is the primary method for accessing the form data parameter list. On first call, the builder is created via the method createFormData().

      Example:

      // Create a client that adds a "foo=bar" form-data parameter on every request. RestClient.Builder<?> builder = RestClient.create(); builder.formData().setDefault("foo", "bar")); RestClient client = builder.build();

      The following convenience methods are also provided for updating the parameters:

      Returns:
      The form data list builder.
    • formData

      public SELF formData(NameValuePair... parts)
      Appends multiple form-data parameters to the request bodies of all URL-encoded form posts.
      Example:

      import static org.apache.juneau.http.HttpParts.*; RestClient client = RestClient .create() .formData( stringPart("foo", "bar"), booleanPart("baz", true) ) .build();

      This is a shortcut for calling formData().append(parts).

      Parameters:
      parts - The form-data parameters.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • formData

      public SELF formData(String name, String value)
      Appends a form-data parameter to all request bodies.
      Example:

      RestClient client = RestClient .create() .formData("foo", "bar") .build();

      This is a shortcut for calling formData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • formData

      public SELF formData(String name, Supplier<String> value)
      Appends a form-data parameter with a dynamic value to all request bodies.
      Example:

      RestClient client = RestClient .create() .formData("foo", ()->"bar") .build();

      This is a shortcut for calling formData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value supplier.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • formDataDefault

      public SELF formDataDefault(NameValuePair... parts)
      Sets default form-data parameter values.

      Uses default values for specified parameters if not otherwise specified on the outgoing requests.

      Example:

      RestClient client = RestClient .create() .formDataDefault(stringPart("foo", ()->"bar")); .build();

      This is a shortcut for calling formData().setDefault(parts).

      Parameters:
      parts - The parts.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • getRootUri

      public String getRootUri()
      Returns the root URI defined for this client.

      Returns null in lieu of an empty string. Trailing slashes are trimmed.

      Returns:
      The root URI defined for this client.
    • getRootUrlSupplier

      Returns the root URL supplier set on this builder.
      Returns:
      The root URL supplier, or null if not set.
    • header

      public SELF header(String name, String value)
      Appends a header to all requests.
      Example:

      RestClient client = RestClient .create() .header("Foo", "bar"); .build();

      This is a shortcut for calling headerData().append(name,value).

      Parameters:
      name - The header name.
      Cannot be null.
      value - The header value.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • header

      public SELF header(String name, Supplier<String> value)
      Appends a header to all requests using a dynamic value.
      Example:

      RestClient client = RestClient .create() .header("Foo", ()->"bar"); .build();

      This is a shortcut for calling headerData().append(name,value).

      Parameters:
      name - The header name.
      Cannot be null.
      value - The header value supplier.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • headers

      public final HeaderList headers()
      Returns the builder for the list of headers that get applied to all requests created by this builder.

      This is the primary method for accessing the request header list. On first call, the builder is created via the method createHeaderData().

      Example:

      // Create a client that adds a "Foo: bar" header on every request. RestClient.Builder<?> builder = RestClient.create(); builder.headerData().setDefault("Foo", "bar")); RestClient client = builder.build();

      The following convenience methods are also provided for updating the headers:

      Returns:
      The header list builder.
    • headers

      public SELF headers(Header... parts)
      Appends multiple headers to all requests.
      Example:

      import static org.apache.juneau.http.HttpHeaders.*; RestClient client = RestClient .create() .headers( ACCEPT_TEXT_XML, stringHeader("Foo", "bar") ) .build();

      This is a shortcut for calling headerData().append(parts).

      Parameters:
      parts - The header to set.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • headersDefault

      public SELF headersDefault(Header... parts)
      Sets default header values.

      Uses default values for specified headers if not otherwise specified on the outgoing requests.

      Example:

      RestClient client = RestClient .create() .headersDefault(stringHeader("Foo", ()->"bar")); .build();

      This is a shortcut for calling headerData().setDefault(parts).

      Parameters:
      parts - The header values.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • serializerSessionOptionsHeader

      Sets a default request header with serializer session options (JSON5 map) for all requests.

      This is a shortcut for headersDefault(basicHeader(RestSharedConstants.HEADER_JuneauSerializerOptions, json5)).

      Parameters:
      json5 - Serializer session options in JSON5 form.
      Can be null (default is not set by this method).
      Returns:
      This object.
    • parserSessionOptionsHeader

      Sets a default request header with parser session options (JSON5 map) for all requests.

      This is a shortcut for headersDefault(basicHeader(RestSharedConstants.HEADER_JuneauParserOptions, json5)).

      Parameters:
      json5 - Parser session options in JSON5 form.
      Can be null (default is not set by this method).
      Returns:
      This object.
    • serializerSessionOptionsHeader

      Convenience for serializerSessionOptionsHeader(String) using a map serialized with JSON5.
      Parameters:
      properties - Property names and values for serializer session options.
      Can be null (treated as an empty map).
      Returns:
      This object.
    • parserSessionOptionsHeader

      public SELF parserSessionOptionsHeader(Map<String,?> properties)
      Convenience for parserSessionOptionsHeader(String) using a map serialized with JSON5.
      Parameters:
      properties - Property names and values for parser session options.
      Can be null (treated as an empty map).
      Returns:
      This object.
    • html

      public SELF html()
      Convenience method for specifying HTML as the marshalling transmission media type.

      POJOs are converted to HTML without any sort of doc wrappers.

      HtmlSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      HtmlParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/html" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/html" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(HtmlSerializer.class).parser(HtmlParser.class).

      Example:

      // Construct a client that uses HTML marshalling. RestClient client = RestClient.create().html().build();

      Returns:
      This object.
    • htmlDoc

      public SELF htmlDoc()
      Convenience method for specifying HTML DOC as the marshalling transmission media type.

      POJOs are converted to fully renderable HTML pages.

      HtmlDocSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      HtmlParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/html" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/html" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(HtmlDocSerializer.class).parser(HtmlParser.class).

      Example:

      // Construct a client that uses HTML Doc marshalling. RestClient client = RestClient.create().htmlDoc().build();

      Returns:
      This object.
    • htmlStrippedDoc

      Convenience method for specifying Stripped HTML DOC as the marshalling transmission media type.

      Same as htmlDoc() but without the header and body tags and page title and description.

      HtmlStrippedDocSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      HtmlParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/html+stripped" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/html+stripped" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(HtmlStrippedDocSerializer.class).parser(HtmlParser.class).

      Example:

      // Construct a client that uses HTML Stripped Doc marshalling. RestClient client = RestClient.create().htmlStrippedDoc().build();

      Returns:
      This object.
    • httpClient

      Sets the HttpClient to be used to handle all HTTP communications with the target server.

      This can be used to bypass the client created by createHttpClient() method.

      Example:

      // Construct a client that uses a customized HttpClient. RestClient client = RestClient .create() .httpClient(HttpClientBuilder.create().build()) .build();

      Parameters:
      value - The HttpClient to be used to handle all HTTP communications with the target server.
      Can be null (a default client will be created).
      Returns:
      This object.
    • httpClientBuilder

      Returns the HTTP client builder.
      Returns:
      The HTTP client builder.
    • httpClientBuilder

      Sets the HttpClientBuilder that will be used to create the HttpClient used by RestClient.

      This can be used to bypass the builder created by createHttpClientBuilder() method.

      Example:

      // Construct a client that uses a customized HttpClientBuilder. RestClient client = RestClient .create() .httpClientBuilder(HttpClientBuilder.create()) .build();

      Notes:
      Parameters:
      value - The HttpClientBuilder that will be used to create the HttpClient used by RestClient.
      Can be null (a default builder will be created).
      Returns:
      This object.
    • httpProcessor

      public SELF httpProcessor(HttpProcessor httpprocessor)
      Assigns HttpProcessor instance.
      Notes:
      Parameters:
      httpprocessor - New property value.
      Returns:
      This object.
      See Also:
    • ignoreErrors

      public SELF ignoreErrors()
      Ignore errors.

      When enabled, HTTP error response codes (e.g. >=400) will not cause a RestCallException to be thrown.

      Note that this is equivalent to builder.errorCodes(x -> false);

      Example:

      // Create a client that doesn't throws a RestCallException when a 500 error occurs. RestClient .create() .ignoreErrors() .build() .get("/error") // Throws a 500 error .run() .assertStatus().is(500);

      Returns:
      This object.
    • ignoreRecursions

      BeanTraverse configuration property:  Ignore recursion errors.

      When enabled, when we encounter the same object when traversing a tree, we set the value to null.

      For example, if a model contains the links A->B->C->A, then the JSON generated will look like the following when BEANTRAVERSE_ignoreRecursions is true...

      {A:{B:{C:null}}}

      Notes:
      • Checking for recursion can cause a small performance penalty.
      Example:

      // Create a JSON client that ignores recursions. RestClient client = RestClient .create() .json() .ignoreRecursions() .build(); // Create a POJO model with a recursive loop. public class A { public Object f; } A a = new A(); a.f = a; // Produces request body "{f:null}" client .post("http://localhost:10000/foo", a) .run();

      See Also:
      Returns:
      This object.
    • initialDepth

      public SELF initialDepth(int value)
      BeanTraverse configuration property:  Initial depth.

      The initial indentation level at the root.

      Useful when constructing document fragments that need to be indented at a certain level when whitespace is enabled.

      Example:

      // Create a REST client with JSON serializer with whitespace enabled and an initial depth of 2. RestClient client = RestClient .create() .json() .ws() .initialDepth(2) .build(); // Our bean to serialize. public class MyBean { public String foo = null; } // Produces request body "\t\t{\n\t\t\t'foo':'bar'\n\t\t}\n" client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Parameters:
      value - The new value for this property.
      The default is 0.
      Returns:
      This object.
    • interceptors

      public SELF interceptors(Class<?>... values) throws Exception
      RestClient configuration property:  Call interceptors.

      Adds an interceptor that can be called to hook into specified events in the lifecycle of a single request.

      Example:

      // Customized interceptor (note you can also extend from BasicRestCallInterceptor as well. public class MyRestCallInterceptor implements RestCallInterceptor { @Override public void onInit(RestRequest req) throws Exception { // Intercept immediately after RestRequest object is created and all headers/query/form-data has been // set on the request from the client. } @Override public void onConnect(RestRequest req, RestResponse res) throws Exception { // Intercept immediately after an HTTP response has been received. } @Override public void onClose(RestRequest req, RestResponse res) throws Exception { // Intercept when the response body is consumed. } } // Create a client with a customized interceptor. RestClient client = RestClient .create() .interceptors(MyRestCallInterceptor.class) .build();

      Notes:
      Parameters:
      values - The values to add to this setting.
      Can be implementations of any of the following:
      Can contain null values (ignored).
      Returns:
      This object.
      Throws:
      Exception - If one or more interceptors could not be created.
    • interceptors

      public SELF interceptors(Object... value)
      Call interceptors.

      Adds an interceptor that gets called immediately after a connection is made.

      Example:

      // Create a client with a customized interceptor. RestClient client = RestClient .create() .interceptors( new RestCallInterceptor() { @Override public void onInit(RestRequest req) throws Exception { // Intercept immediately after RestRequest object is created and all headers/query/form-data has been // set on the request from the client. } @Override public void onConnect(RestRequest req, RestResponse res) throws Exception { // Intercept immediately after an HTTP response has been received. } @Override public void onClose(RestRequest req, RestResponse res) throws Exception { // Intercept when the response body is consumed. } } ) .build();

      Notes:
      Parameters:
      value - The values to add to this setting.
      Can be implementations of any of the following:
      Can contain null values (ignored).
      Returns:
      This object.
    • json

      public SELF json()
      Convenience method for specifying JSON as the marshalling transmission media type.

      JsonSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      JsonParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "application/json" unless overridden via headers(), or per-request via RestRequest.header(Header)}.

      Content-Type request header will be set to "application/json" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as xml() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(JsonSerializer.class).parser(JsonParser.class).

      Example:

      // Construct a client that uses JSON marshalling. RestClient client = RestClient.create().json().build();

      Returns:
      This object.
    • json5

      public SELF json5()
      Convenience method for specifying Simplified JSON as the marshalling transmission media type.

      Simplified JSON is typically useful for automated tests because you can do simple string comparison of results without having to escape lots of quotes.

      Json5Serializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      Json5Parser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "application/json5" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "application/json5" unless overridden via headers(), or per-request via RestRequest.header(Header).

      A server that only handles JSON may reply 406 Not Acceptable or 415 Unsupported Media Type to these JSON5 media types.

      Can be combined with other marshaller setters such as xml() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(Json5Serializer.class).parser(Json5Parser.class).

      Example:

      // Construct a client that uses Simplified JSON marshalling. RestClient client = RestClient.create().json5().build();

      Returns:
      This object.
    • jcs

      public SELF jcs()
      Convenience method for specifying JCS (JSON Canonicalization Scheme, RFC 8785) as the marshalling transmission media type.

      JcsSerializer will be used to serialize POJOs to request bodies. JsonParser will be used to parse POJOs from response bodies (JCS output is valid JSON).

      Accept and Content-Type will be set to "application/jcs+json".

      Identical to calling serializer(JcsSerializer.class).parser(JsonParser.class).

      Returns:
      This object.
    • keepAliveStrategy

      Assigns ConnectionKeepAliveStrategy instance.
      Parameters:
      keepAliveStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • keepHttpClientOpen

      RestClient configuration property:  Keep HttpClient open.

      Don't close this client when the RestClient.close() method is called.

      Example:

      // Create a client with a customized client and don't close the client service. RestClient client = RestClient .create() .httpClient(myHttpClient) .keepHttpClientOpen() .build(); client.closeQuietly(); // Customized HttpClient won't be closed.

      Notes:
      • When combined with connectionManagerShared(true), the client's internal pool for SSRF-guard-active @Remote calls (see createConnectionManager()) and the connection manager the default createConnectionManager() built are not shut down either, and nothing else shuts them down; their connections stay open until they are closed as idle or the JVM exits.
      Returns:
      This object.
    • keepNullProperties

      Serializer configuration property:  Don't trim null bean property values.

      When enabled, null bean values will be serialized to the output.

      Notes:
      • Not enabling this setting will cause Maps with null values to be lost during parsing.
      Example:

      // Create a REST client with JSON serializer that serializes null properties. RestClient client = RestClient .create() .json() .keepNullProperties() .build(); // Our bean to serialize. public class MyBean { public String foo = null; } // Request body will contain: {foo:null} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • logger

      public SELF logger(Logger value)
      Logger.

      Specifies the logger to use for logging.

      If not specified, uses the following logger:

      Logger.getLogger(RestClient.class.getName());

      Example:

      // Construct a client that logs messages to a special logger. RestClient client = RestClient .create() .logger(Logger.getLogger("MyLogger")) // Log to MyLogger logger. .logToConsole() // Also log to console. .logRequests(FULL, WARNING) // Log requests with full detail at WARNING level. .build();

      Parameters:
      value - The logger to use for logging.
      Can be null (defaults to Logger.getLogger(RestClient.class.getName())).
      Returns:
      This object.
    • logRequests

      Log requests.

      Causes requests/responses to be logged at the specified log level at the end of the request.

      SIMPLE detail produces a log message like the following:

      POST http://localhost:10000/testUrl, HTTP/1.1 200 OK

      FULL detail produces a log message like the following:

      === HTTP Call (outgoing) ======================================================= === REQUEST === POST http://localhost:10000/testUrl ---request headers--- Debug: true No-Trace: true Accept: application/json ---request entity--- Content-Type: application/json ---request content--- {"foo":"bar","baz":123} === RESPONSE === HTTP/1.1 200 OK ---response headers--- Content-Type: application/json;charset=utf-8 Content-Length: 21 Server: Jetty(8.1.0.v20120127) ---response content--- {"message":"OK then"} === END ========================================================================

      By default, the message is logged to the default logger. It can be logged to a different logger via the logger(Logger) method or logged to the console using the logToConsole() method.

      Parameters:
      detail - The detail level of logging.
      level - The log level.
      test - A predicate to use per-request to see if the request should be logged. If null, always logs.
      Returns:
      This object.
    • logToConsole

      public SELF logToConsole()
      Log to console.

      Specifies to log messages to the console.

      Example:

      // Construct a client that logs messages to a special logger. RestClient client = RestClient .create() .logToConsole() .logRequests(FULL, INFO) // Level is ignored when logging to console. .build();

      Returns:
      This object.
    • marshaller

      public SELF marshaller(Marshaller value)
      RestClient configuration property:  Marshaller

      Shortcut for specifying the serializers and parsers using the serializer and parser defined in a marshaller.

      Notes:
      Example:

      // Create a client that uses Simplified-JSON transport using an existing marshaller. RestClient client = RestClient .create() .marshaller(Json5.DEFAULT_READABLE) .build();

      Parameters:
      value - The values to add to this setting.
      Can be null (value will not be set, existing serializers and parsers will be kept).
      Returns:
      This object.
    • marshallers

      public SELF marshallers(Marshaller... value)
      RestClient configuration property:  Marshalls

      Shortcut for specifying the serializers and parsers using the serializer and parser defined in a marshaller.

      Notes:
      Example:

      // Create a client that uses JSON and XML transport using existing marshalls. RestClient client = RestClient .create() .marshaller(Json.DEFAULT_READABLE, Xml.DEFAULT_READABLE) .build();

      Parameters:
      value - The values to add to this setting.
      Can contain null values (ignored).
      Returns:
      This object.
    • maxConnPerRoute

      public SELF maxConnPerRoute(int maxConnPerRoute)
      Assigns maximum connection per route value.
      Notes:
      Parameters:
      maxConnPerRoute - New property value.
      Returns:
      This object.
      See Also:
    • maxConnTotal

      public SELF maxConnTotal(int maxConnTotal)
      Assigns maximum total connection value.
      Notes:
      Parameters:
      maxConnTotal - New property value.
      Returns:
      This object.
      See Also:
    • maxDepth

      public SELF maxDepth(int value)
      BeanTraverse configuration property:  Max serialization depth.

      When enabled, abort traversal if specified depth is reached in the POJO tree.

      If this depth is exceeded, an exception is thrown.

      This prevents stack overflows from occurring when trying to traverse models with recursive references.

      Example:

      // Create a REST client with JSON serializer that throws an exception if the depth reaches greater than 20. RestClient client = RestClient .create() .json() .maxDepth(20) .build();

      See Also:
      Parameters:
      value - The new value for this property.
      The default is 100.
      Returns:
      This object.
    • maxIndent

      public SELF maxIndent(int value)
      WriterSerializer configuration property:  Maximum indentation.

      Specifies the maximum indentation level in the serialized document.

      Notes:
      • This setting does not apply to the RDF serializers.
      Example:

      // Create a REST client with JSON serializer that indents a maximum of 20 tabs. RestClient client = RestClient .create() .json() .ws() // Enable whitespace .maxIndent(20) .build();

      See Also:
      Parameters:
      value - The new value for this property.
      The default is 100.
      Returns:
      This object.
    • mediaType

      public SELF mediaType(MediaType value)
      Appends the Accept and Content-Type headers on all requests made by this client.

      Headers are appended to the end of the current header list.

      This is a shortcut for calling headerData().append(Accept.of(value), ContentType.of(value)).

      Overrides:
      mediaType in class MarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>
      Parameters:
      value - The new header values.
      Can be null (no Accept or Content-Type headers will be added).
      Returns:
      This object.
      See Also:
    • mediaType

      public SELF mediaType(String value)
      Appends the Accept and Content-Type headers on all requests made by this client.

      Headers are appended to the end of the current header list.

      This is a shortcut for calling headerData().append(Accept.of(value), ContentType.of(value)).

      Parameters:
      value - The new header values.
      Can be null (no Accept or Content-Type headers will be added).
      Returns:
      This object.
      See Also:
    • bson

      public SELF bson()
      Convenience method for specifying BSON as the marshalling transmission media type.

      BSON (Binary JSON) is the format used by MongoDB. Identical to calling serializer(BsonSerializer.class).parser(BsonParser.class).

      Returns:
      This object.
    • msgPack

      public SELF msgPack()
      Convenience method for specifying MessagePack as the marshalling transmission media type.

      MessagePack is a binary equivalent to JSON that takes up considerably less space than JSON.

      MsgPackSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      MsgPackParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "application/msgpack" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "application/msgpack" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(MsgPackSerializer.class).parser(MsgPackParser.class).

      Example:

      // Construct a client that uses MessagePack marshalling. RestClient client = RestClient.create().msgPack().build();

      Returns:
      This object.
    • noTrace

      public SELF noTrace()
      When called, No-Trace: true is added to requests.

      This gives the opportunity for the servlet to not log errors on invalid requests. This is useful for testing purposes when you don't want your log file to show lots of errors that are simply the results of testing.

      It's up to the server to decide whether to allow for this. The BasicTestRestLogger class watches for this header and prevents logging of status 400+ responses to prevent needless logging of test scenarios.

      Returns:
      This object.
      See Also:
    • oapiCollectionFormat

      OpenApiCommon configuration property:  Default collection format for HTTP parts.

      Specifies the collection format to use for HTTP parts when not otherwise specified via Schema.collectionFormat() for the OpenAPI serializer and parser on this client.

      Example:

      // Create a REST client with CSV format for http parts. RestClient client = RestClient .create() .collectionFormat(CSV) .build(); // An arbitrary data structure. AList list = AList.of( "foo", "bar", AMap.of( "baz", AList.of("qux","true","123") ) ); // Set a header with a comma-separated list. client .get("/uri") .header("Foo", list) // Will be serialized as: foo=bar,baz=qux\,true\,123 .run();

      • HttpPartCollectionFormat
        • CSV - (default) Comma-separated values (e.g. "foo,bar").
        • SSV - Space-separated values (e.g. "foo bar").
        • TSV - Tab-separated values (e.g. "foo\tbar").
        • PIPES - Pipe-separated values (e.g. "foo|bar").
        • MULTI - Corresponds to multiple parameter instances instead of multiple values for a single instance (e.g. "foo=bar&foo=baz").
        • UONC - UON collection notation (e.g. "@(foo,bar)").
      See Also:
      Parameters:
      value - The new value for this property.
      The default value is HttpPartCollectionFormat.NO_COLLECTION_FORMAT.
      Cannot be null.
      Returns:
      This object.
    • oapiFormat

      public SELF oapiFormat(HttpPartFormat value)
      OpenApiCommon configuration property:  Default OpenAPI format for HTTP parts.

      Specifies the format to use for HTTP parts when not otherwise specified via Schema.format() for the OpenAPI serializer and parser on this client.

      Example:

      // Create a REST client with UON part serialization and parsing. RestClient client = RestClient .create() .oapiFormat(UON) .build(); // Set a header with a value in UON format. client .get("/uri") .header("Foo", "bar baz") // Will be serialized as: 'bar baz' .run();

      See Also:
      Parameters:
      value - The new value for this property.
      The default value is HttpPartFormat.NO_FORMAT.
      Cannot be null.
      Returns:
      This object.
    • openApi

      public SELF openApi()
      Convenience method for specifying OpenAPI as the marshalling transmission media type.

      OpenAPI is a language that allows serialization to formats that use HttpPartSchema objects to describe their structure.

      OpenApiSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      OpenApiParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/openapi" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/openapi" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(OpenApiSerializer.class).parser(OpenApiParser.class).

      Example:

      // Construct a client that uses OpenAPI marshalling. RestClient client = RestClient.create().openApi().build();

      Returns:
      This object.
    • paramFormat

      public SELF paramFormat(ParamFormat value)
      UonSerializer configuration property:  Parameter format.

      Specifies the format of parameters when using the UrlEncodingSerializer to serialize Form Posts.

      Specifies the format to use for GET parameter keys and values.

      Example:

      // Create a REST client with URL-Encoded serializer that serializes values in plain-text format. RestClient client = RestClient .create() .urlEnc() .paramFormat(PLAINTEXT) .build(); // An arbitrary data structure. AMap map = AMap.of( "foo", "bar", "baz", new String[]{"qux", "true", "123"} ); // Request body will be serialized as: foo=bar,baz=qux,true,123 client .post("/uri", map) .run();

      See Also:
      Parameters:
      value - The new value for this property.
      Cannot be null.
      Returns:
      This object.
    • paramFormatPlain

      UonSerializer configuration property:  Parameter format.

      Specifies the format of parameters when using the UrlEncodingSerializer to serialize Form Posts.

      Specifies plaintext as the format to use for GET parameter keys and values.

      Example:

      // Create a REST client with URL-Encoded serializer that serializes values in plain-text format. RestClient client = RestClient .create() .urlEnc() .build(); // An arbitrary data structure. AMap map = AMap.of( "foo", "bar", "baz", new String[]{"qux", "true", "123"} ); // Request body will be serialized as: foo=bar,baz=qux,true,123 client .post("/uri", map) .run();

      See Also:
      Returns:
      This object.
    • parser

      public SELF parser(Class<? extends Parser> value)
      Parser.

      Associates the specified Parser with the HTTP client.

      The parser is used to parse the HTTP response body into a POJO.

      Notes:
      Example:

      // Create a client that uses JSON transport for response bodies. RestClient client = RestClient .create() .parser(JsonParser.class) .build();

      Parameters:
      value - The new value for this setting.
      The default value is JsonParser.DEFAULT.
      Returns:
      This object.
    • parser

      public SELF parser(Parser value)
      Parser.

      Associates the specified Parser with the HTTP client.

      The parser is used to parse the HTTP response body into a POJO.

      Notes:
      Example:

      // Create a client that uses a predefined JSON parser for response bodies. RestClient client = RestClient .create() .parser(JsonParser.DEFAULT) .build();

      Parameters:
      value - The new value for this setting.
      The default value is JsonParser.DEFAULT.
      Cannot be null.
      Returns:
      This object.
    • parsers

      public final ParserSet.Builder parsers()
      Returns the parser group sub-builder.
      Returns:
      The parser group sub-builder.
    • parsers

      public SELF parsers(Class<? extends Parser>... value)
      Parsers.

      Associates the specified Parsers with the HTTP client.

      The parsers are used to parse the HTTP response body into a POJO.

      The parser that best matches the Accept header will be used to parse the response body.
      If no Accept header is specified, the first parser in the list will be used.

      Notes:
      Example:

      // Create a client that uses JSON and XML transport for response bodies. RestClient client = RestClient .create() .parser(JsonParser.class, XmlParser.class) .build();

      Parameters:
      value - The new value for this setting.
      The default value is JsonParser.DEFAULT.
      Returns:
      This object.
    • parsers

      public SELF parsers(Parser... value)
      Parsers.

      Associates the specified Parsers with the HTTP client.

      The parsers are used to parse the HTTP response body into a POJO.

      The parser that best matches the Accept header will be used to parse the response body.
      If no Accept header is specified, the first parser in the list will be used.

      Notes:
      Example:

      // Create a client that uses JSON and XML transport for response bodies. RestClient client = RestClient .create() .parser(JsonParser.DEFAULT, XmlParser.DEFAULT) .build();

      Parameters:
      value - The new value for this setting.
      The default value is JsonParser.DEFAULT.
      Returns:
      This object.
    • partParser

      Returns the part parser sub-builder.
      Returns:
      The part parser sub-builder.
    • partParser

      public SELF partParser(Class<? extends HttpPartParser> value)
      Part parser.

      The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.

      The default part parser is OpenApiParser which allows for schema-driven marshalling.

      Example:

      // Create a client that uses UON format by default for incoming HTTP parts. RestClient client = RestClient .create() .partParser(UonParser.class) .build();

      Parameters:
      value - The new value for this setting.
      The default value is OpenApiParser.
      Cannot be null.
      Returns:
      This object.
    • partParser

      public SELF partParser(HttpPartParser value)
      Part parser.

      The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.

      The default part parser is OpenApiParser which allows for schema-driven marshalling.

      Example:

      // Create a client that uses UON format by default for incoming HTTP parts. RestClient client = RestClient .create() .partParser(UonParser.DEFAULT) .build();

      Parameters:
      value - The new value for this setting.
      The default value is OpenApiParser.
      Cannot be null.
      Returns:
      This object.
    • partSerializer

      Returns the part serializer sub-builder.
      Returns:
      The part serializer sub-builder.
    • partSerializer

      public SELF partSerializer(Class<? extends HttpPartSerializer> value)
      Part serializer.

      The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.

      The default part serializer is OpenApiSerializer which allows for schema-driven marshalling.

      Example:

      // Create a client that uses UON format by default for outgoing HTTP parts. RestClient client = RestClient .create() .partSerializer(UonSerializer.class) .build();

      Parameters:
      value - The new value for this setting.
      The default value is OpenApiSerializer.
      Cannot be null.
      Returns:
      This object.
    • partSerializer

      Part serializer.

      The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.

      The default part serializer is OpenApiSerializer which allows for schema-driven marshalling.

      Example:

      // Create a client that uses UON format by default for outgoing HTTP parts. RestClient client = RestClient .create() .partSerializer(UonSerializer.DEFAULT) .build();

      Parameters:
      value - The new value for this setting.
      The default value is OpenApiSerializer.
      Cannot be null.
      Returns:
      This object.
    • pathData

      public final PartList pathData()
      Returns the builder for the list of path data parameters that get applied to all requests created by this builder.

      This is the primary method for accessing the path data parameter list. On first call, the builder is created via the method createFormData().

      Example:

      // Create a client that uses "bar" for the "{foo}" path variable on every request. RestClient.Builder<?> builder = RestClient.create(); builder.pathData().setDefault("foo", "bar")); RestClient client = builder.build();

      The following convenience methods are also provided for updating the parameters:

      Returns:
      The form data list builder.
    • pathData

      public SELF pathData(NameValuePair... parts)
      Sets multiple path parameters on all requests.
      Example:

      import static org.apache.juneau.http.HttpParts.*; RestClient client = RestClient .create() .pathData( stringPart("foo", "bar"), booleanPart("baz", true) ) .build();

      This is a shortcut for calling pathData().append(parts).

      Parameters:
      parts - The path parameters.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • pathData

      public SELF pathData(String name, String value)
      Appends a path parameter to all request bodies.
      Example:

      RestClient client = RestClient .create() .pathData("foo", "bar") .build();

      This is a shortcut for calling pathData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • pathData

      public SELF pathData(String name, Supplier<String> value)
      Sets a path parameter with a dynamic value to all request bodies.
      Example:

      RestClient client = RestClient .create() .pathData("foo", ()->"bar") .build();

      This is a shortcut for calling pathData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value supplier.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • pathDataDefault

      public SELF pathDataDefault(NameValuePair... parts)
      Sets default path parameter values.

      Uses default values for specified parameters if not otherwise specified on the outgoing requests.

      Example:

      RestClient client = RestClient .create() .pathDataDefault(stringPart("foo", ()->"bar")); .build();

      This is a shortcut for calling pathData().setDefault(parts).

      Parameters:
      parts - The parts.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • plainText

      public SELF plainText()
      Convenience method for specifying Plain Text as the marshalling transmission media type.

      Plain text marshalling typically only works on simple POJOs that can be converted to and from strings using swaps, swap methods, etc...

      PlainTextSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      PlainTextParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/plain" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/plain" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(PlainTextSerializer.class).parser(PlainTextParser.class).

      Example:

      // Construct a client that uses Plain Text marshalling. RestClient client = RestClient.create().plainText().build();

      Returns:
      This object.
    • pooled

      public SELF pooled()
      When called, the createConnectionManager() method will return a PoolingHttpClientConnectionManager instead of a BasicHttpClientConnectionManager.
      Example:

      // Construct a client that uses pooled connections. RestClient client = RestClient .create() .pooled() .build();

      Returns:
      This object.
    • proxy

      public SELF proxy(HttpHost proxy)
      Assigns default proxy value.
      Notes:
      • This value can be overridden by the routePlanner(HttpRoutePlanner) method.
      • Through a proxy, the SSRF guard's pin-on-connect would check the proxy's address rather than the target's, so an SSRF-guard-active @Remote call (one without the allowPrivateUrls opt-in) on a proxy route is refused. This applies to any proxy route, including one chosen by a route planner or the proxy system properties (useSystemProperties()). Ordinary requests are unaffected.
      Parameters:
      proxy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • proxyAuthenticationStrategy

      Assigns AuthenticationStrategy instance for proxy authentication.
      Parameters:
      proxyAuthStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • publicSuffixMatcher

      public SELF publicSuffixMatcher(PublicSuffixMatcher publicSuffixMatcher)
      Assigns file containing public suffix matcher.
      Notes:
      Parameters:
      publicSuffixMatcher - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • queryData

      public final PartList queryData()
      Returns the builder for the list of query parameters that get applied to all requests created by this builder.

      This is the primary method for accessing the query parameter list. On first call, the builder is created via the method createQueryData().

      Example:

      // Create a client that adds a "foo=bar" query parameter on every request. RestClient.Builder<?> builder = RestClient.create(); builder.queryData().setDefault("foo", "bar")); RestClient client = builder.build();

      The following convenience methods are also provided for updating the parameters:

      Returns:
      The query data list builder.
    • queryData

      public SELF queryData(NameValuePair... parts)
      Appends multiple query parameters to the URI of all requests.
      Example:

      import static org.apache.juneau.http.HttpParts.*; RestClient client = RestClient .create() .queryData( stringPart("foo", "bar"), booleanPart("baz", true) ) .build();

      This is a shortcut for calling queryData().append(parts).

      Parameters:
      parts - The query parameters.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • queryData

      public SELF queryData(String name, String value)
      Appends a query parameter to the URI.
      Example:

      RestClient client = RestClient .create() .queryData("foo", "bar") .build();

      This is a shortcut for calling queryData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • queryData

      public SELF queryData(String name, Supplier<String> value)
      Appends a query parameter with a dynamic value to the URI.
      Example:

      RestClient client = RestClient .create() .queryData("foo", ()->"bar") .build();

      This is a shortcut for calling queryData().append(name,value).

      Parameters:
      name - The parameter name.
      Cannot be null.
      value - The parameter value supplier.
      Can be null (null value will be serialized).
      Returns:
      This object.
      See Also:
    • queryDataDefault

      public SELF queryDataDefault(NameValuePair... parts)
      Sets default query parameter values.

      Uses default values for specified parameters if not otherwise specified on the outgoing requests.

      Example:

      RestClient client = RestClient .create() .queryDataDefault(stringPart("foo", ()->"bar")); .build();

      This is a shortcut for calling queryData().setDefault(parts).

      Parameters:
      parts - The parts.
      Can contain null values (ignored).
      Returns:
      This object.
      See Also:
    • serializerSessionOptionsQueryDefault

      Sets a default query parameter with serializer session options (UON map) for all requests.

      This is a shortcut for queryDataDefault(stringPart(RestSharedConstants.QUERY_juneauSerializerOptions, uon)).

      Parameters:
      uon - Serializer session options in UON form.
      Can be null (default is not set by this method).
      Returns:
      This object.
    • parserSessionOptionsQueryDefault

      Sets a default query parameter with parser session options (UON map) for all requests.

      This is a shortcut for queryDataDefault(stringPart(RestSharedConstants.QUERY_juneauParserOptions, uon)).

      Parameters:
      uon - Parser session options in UON form.
      Can be null (default is not set by this method).
      Returns:
      This object.
    • serializerSessionOptionsQueryDefault

      Parameters:
      properties - Property names and values for serializer session options.
      Can be null (treated as an empty map).
      Returns:
      This object.
    • parserSessionOptionsQueryDefault

      Parameters:
      properties - Property names and values for parser session options.
      Can be null (treated as an empty map).
      Returns:
      This object.
    • quoteChar

      public SELF quoteChar(char value)
      WriterSerializer configuration property:  Quote character.

      Specifies the character to use for quoting attributes and values.

      Notes:
      • This setting does not apply to the RDF serializers.
      Example:

      // Create a REST client with JSON serializer that uses single quotes. RestClient client = RestClient .create() .json() .quoteChar('\'') .build(); // A bean with a single property public class MyBean { public String foo = "bar"; } // Request body will contain: {'foo':'bar'} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Parameters:
      value - The new value for this property.
      The default is '"'.
      Returns:
      This object.
    • redirectStrategy

      public SELF redirectStrategy(RedirectStrategy redirectStrategy)
      Assigns RedirectStrategy instance.
      Notes:
      Parameters:
      redirectStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • requestExecutor

      Assigns HttpRequestExecutor instance.
      Parameters:
      requestExec - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • retryHandler

      public SELF retryHandler(HttpRequestRetryHandler retryHandler)
      Assigns HttpRequestRetryHandler instance.
      Notes:
      Parameters:
      retryHandler - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • rootUrl

      public SELF rootUrl(Object value)
      RestClient configuration property:  Root URI.

      When set, relative URI strings passed in through the various rest call methods (e.g. RestClient.get(Object) will be prefixed with the specified root.
      This root URI is ignored on those methods if you pass in a URL, URI, or an absolute URI string.

      Example:

      // Create a client that uses UON format by default for HTTP parts. RestClient client = RestClient .create() .rootUrl("http://localhost:10000/foo") .build(); Bar bar = client .get("/bar") // Relative to http://localhost:10000/foo .run() .getContent().as(Bar.class);

      Parameters:
      value - The root URI to prefix to relative URI strings.
      Trailing slashes are trimmed.
      Usually a String but you can also pass in URI and URL objects as well.
      Can be null (no root URL will be set).
      Returns:
      This object.
    • rootUrl

      public SELF rootUrl(Supplier<String> value)
      Sets the root URL using a supplier, allowing the URL to be computed dynamically at request time.

      The supplier is called on every request, so the URL can change between requests. No build-time validation is performed; invalid values will surface as errors when requests are made.

      Three common patterns are supported:

      • Swappable reference — Use an AtomicReference when you need to point the client at a different host at any time:

        AtomicReference<String> urlRef = new AtomicReference<>("https://host1"); RestClient client = RestClient.create().rootUrl(urlRef::get).build(); // Switch to a different host at runtime. urlRef.set("https://host2");

      • Refreshable cached value — Use Memoizer (via Suppliers.memoizer()) when computing the URL is expensive (e.g. service discovery) and you want it cached until explicitly refreshed:

        Memoizer<String> url = memoizer(() -> serviceDiscovery.findUrl("my-service")); RestClient client = RestClient.create().rootUrl(url).build(); // Force re-evaluation on the next request (e.g. after a failover). url.reset();

      • Purely dynamic — Use a plain lambda when the URL must be re-evaluated on every request:

        RestClient client = RestClient.create().rootUrl(() -> config.getRootUrl()).build();

      Parameters:
      value - A supplier that returns the root URI to prefix to relative URI strings.
      Can be null (no root URL will be set).
      Returns:
      This object.
    • routePlanner

      public SELF routePlanner(HttpRoutePlanner routePlanner)
      Assigns HttpRoutePlanner instance.
      Parameters:
      routePlanner - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • schemePortResolver

      public SELF schemePortResolver(SchemePortResolver schemePortResolver)
      Assigns SchemePortResolver instance.
      Parameters:
      schemePortResolver - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • serializer

      public SELF serializer(Class<? extends Serializer> value)
      Serializer.

      Associates the specified Serializer with the HTTP client.

      The serializer is used to serialize POJOs into the HTTP request body.

      Notes:
      Example:

      // Create a client that uses JSON transport for request bodies. RestClient client = RestClient .create() .serializer(JsonSerializer.class) .sortCollections() // Sort any collections being serialized. .build();

      Parameters:
      value - The new value for this setting.
      The default is JsonSerializer.
      Returns:
      This object.
    • serializer

      public SELF serializer(Serializer value)
      Serializer.

      Associates the specified Serializer with the HTTP client.

      The serializer is used to serialize POJOs into the HTTP request body.

      Notes:
      Example:

      // Create a client that uses a predefined JSON serializer request bodies. RestClient client = RestClient .create() .serializer(JsonSerializer.DEFAULT_READABLE) .build();

      Parameters:
      value - The new value for this setting.
      The default is JsonSerializer.
      Cannot be null.
      Returns:
      This object.
    • serializers

      Returns the serializer group sub-builder.
      Returns:
      The serializer group sub-builder.
    • serializers

      public SELF serializers(Class<? extends Serializer>... value)
      Serializers.

      Associates the specified Serializers with the HTTP client.

      The serializer is used to serialize POJOs into the HTTP request body.

      The serializer that best matches the Content-Type header will be used to serialize the request body.
      If no Content-Type header is specified, the first serializer in the list will be used.

      Notes:
      Example:

      // Create a client that uses JSON and XML transport for request bodies. RestClient client = RestClient .create() .serializers(JsonSerializer.class, XmlSerializer.class) .sortCollections() // Sort any collections being serialized. .build();

      Parameters:
      value - The new value for this setting.
      The default is JsonSerializer.
      Returns:
      This object.
    • serializers

      public SELF serializers(Serializer... value)
      Serializers.

      Associates the specified Serializers with the HTTP client.

      The serializer is used to serialize POJOs into the HTTP request body.

      The serializer that best matches the Content-Type header will be used to serialize the request body.
      If no Content-Type header is specified, the first serializer in the list will be used.

      Notes:
      Example:

      // Create a client that uses predefined JSON and XML serializers for request bodies. RestClient client = RestClient .create() .serializers(JsonSerializer.DEFAULT_READABLE, XmlSerializer.DEFAULT_READABLE) .build();

      Parameters:
      value - The new value for this setting.
      The default is JsonSerializer.
      Returns:
      This object.
    • serviceUnavailableRetryStrategy

      Parameters:
      serviceUnavailStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • skipEmptyFormData

      Skip empty form data.

      When enabled, form data consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Returns:
      This object.
    • skipEmptyFormData

      public SELF skipEmptyFormData(boolean value)
      Skip empty form data.

      When enabled, form data consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Parameters:
      value - The new value for this setting.
      The default is false.
      Returns:
      This object.
    • skipEmptyHeaderData

      Skip empty header data.

      When enabled, headers consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Returns:
      This object.
    • skipEmptyHeaderData

      public SELF skipEmptyHeaderData(boolean value)
      Skip empty header data.

      When enabled, headers consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Parameters:
      value - The new value for this setting.
      The default is false.
      Returns:
      This object.
    • skipEmptyQueryData

      Skip empty query data.

      When enabled, query parameters consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Returns:
      This object.
    • skipEmptyQueryData

      public SELF skipEmptyQueryData(boolean value)
      Skip empty query data.

      When enabled, query parameters consisting of empty strings will be skipped on requests. Note that null values are already skipped.

      The Schema.skipIfEmpty() annotation overrides this setting.

      Parameters:
      value - The new value for this setting.
      The default is false.
      Returns:
      This object.
    • sortCollections

      Serializer configuration property:  Sort arrays and collections alphabetically.

      When enabled, copies and sorts the contents of arrays and collections before serializing them.

      Note that this introduces a performance penalty since it requires copying the existing collection.

      Example:

      // Create a REST client with JSON serializer that sorts arrays and collections before serialization. RestClient client = RestClient .create() .json() .sortCollections() .build(); // An unsorted array String[] array = {"foo","bar","baz"} // Request body will contain: ["bar","baz","foo"] client .post("http://localhost:10000/foo", array) .run();

      See Also:
      Returns:
      This object.
    • sortMaps

      public SELF sortMaps()
      Serializer configuration property:  Sort maps alphabetically.

      When enabled, copies and sorts the contents of maps by their keys before serializing them.

      Note that this introduces a performance penalty.

      Example:

      // Create a REST client with JSON serializer that sorts maps before serialization. RestClient client = RestClient .create() .json() .sortMaps() .build(); // An unsorted map. AMap map = AMap.of("foo",1,"bar",2,"baz",3); // Request body will contain: {"bar":2,"baz":3,"foo":1} client .post("http://localhost:10000/foo", map) .run();

      See Also:
      Returns:
      This object.
    • sq

      public SELF sq()
      WriterSerializer configuration property:  Quote character.

      Specifies to use single quotes for quoting attributes and values.

      Notes:
      • This setting does not apply to the RDF serializers.
      Example:

      // Create a REST client with JSON serializer that uses single quotes. RestClient client = RestClient .create() .json() .sq() .build(); // A bean with a single property public class MyBean { public String foo = "bar"; } // Request body will contain: {'foo':'bar'} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • sslContext

      public SELF sslContext(SSLContext sslContext)
      Assigns SSLContext instance.

      The context (for example one initialized with a custom trust store) is used for https connections, with the hostname verifier if one is set, or the default one.

      Notes:
      Parameters:
      sslContext - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • sslHostnameVerifier

      public SELF sslHostnameVerifier(HostnameVerifier hostnameVerifier)
      Assigns HostnameVerifier instance.
      Notes:
      Parameters:
      hostnameVerifier - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • sslSocketFactory

      Assigns LayeredConnectionSocketFactory instance.

      The factory is used for https connections, in place of one built from the SSL context and hostname verifier.

      Notes:
      Parameters:
      sslSocketFactory - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • targetAuthenticationStrategy

      Assigns AuthenticationStrategy instance for target host authentication.
      Parameters:
      targetAuthStrategy - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • trimEmptyCollections

      Serializer configuration property:  Trim empty lists and arrays.

      When enabled, empty lists and arrays will not be serialized.

      Note that enabling this setting has the following effects on parsing:

      • Map entries with empty list values will be lost.
      • Bean properties with empty list values will not be set.
      Example:

      // Create a serializer that skips empty arrays and collections. WriterSerializer serializer = JsonSerializer .create() .trimEmptyCollections() .build(); // A bean with a field with an empty array. public class MyBean { public String[] foo = {}; } // Request body will contain: {} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • trimEmptyMaps

      public SELF trimEmptyMaps()
      Serializer configuration property:  Trim empty maps.

      When enabled, empty map values will not be serialized to the output.

      Note that enabling this setting has the following effects on parsing:

      • Bean properties with empty map values will not be set.
      Example:

      // Create a REST client with JSON serializer that skips empty maps. RestClient client = RestClient .create() .json() .trimEmptyMaps() .build(); // A bean with a field with an empty map. public class MyBean { public AMap foo = AMap.of(); } // Request body will contain: {} client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • trimStringsOnRead

      Parser configuration property:  Trim parsed strings.

      When enabled, string values will be trimmed of whitespace using String.trim() before being added to the POJO.

      Example:

      // Create a REST client with JSON parser with trim-strings enabled. RestClient client = RestClient .create() .json() .trimStringsOnRead() .build(); // Try to parse JSON containing {" foo ":" bar "}. Map<String,String> map = client .get("/pathToJson") .run() .getContent().as(HashMap.class, String.class, String.class); // Make sure strings are trimmed. assertEquals("bar", map.get("foo"));

      See Also:
      Returns:
      This object.
    • trimStringsOnWrite

      Serializer configuration property:  Trim strings.

      When enabled, string values will be trimmed of whitespace using String.trim() before being serialized.

      Example:

      // Create a REST client with JSON serializer that trims strings before serialization. RestClient client = RestClient .create() .json() .trimStrings() .build(); // A map with space-padded keys/values AMap map = AMap.of(" foo ", " bar "); // Request body will contain: {"foo":"bar"} client .post("http://localhost:10000/foo", map) .run();

      See Also:
      Returns:
      This object.
    • universal

      public SELF universal()
      Convenience method for specifying all available transmission types.

      All basic Juneau serializers will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      All basic Juneau parsers will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header must be set via headers(), or per-request via RestRequest.header(Header) in order for the correct parser to be selected.

      Content-Type request header must be set via headers(), or per-request via RestRequest.header(Header) in order for the correct serializer to be selected.

      Similar to calling json().json5().html().xml().uon().urlEnc().openApi().msgPack().plainText().

      Example:

      // Construct a client that uses universal marshalling. RestClient client = RestClient.create().universal().build();

      Returns:
      This object.
    • uon

      public SELF uon()
      Convenience method for specifying UON as the marshalling transmission media type.

      UON is Url-Encoding Object notation that is equivalent to JSON but suitable for transmission as URL-encoded query and form post values.

      UonSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      UonParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/uon" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/uon" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(UonSerializer.class).parser(UonParser.class).

      Example:

      // Construct a client that uses UON marshalling. RestClient client = RestClient.create().uon().build();

      Returns:
      This object.
    • uriContext

      public SELF uriContext(UriContext value)
      Serializer configuration property:  URI context bean.

      Bean used for resolution of URIs to absolute or root-relative form.

      Example:

      // Our URI contextual information. String authority = "http://localhost:10000"; String contextRoot = "/myContext"; String servletPath = "/myServlet"; String pathInfo = "/foo"; // Create a UriContext object. UriContext uriContext = new UriContext(authority, contextRoot, servletPath, pathInfo); // Create a REST client with JSON serializer and associate our context. RestClient client = RestClient .create() .json() .uriContext(uriContext) .uriRelativity(RESOURCE) // Assume relative paths are relative to servlet. .uriResolution(ABSOLUTE) // Serialize URIs as absolute paths. .build(); // A relative URI URI uri = new URI("bar"); // Request body will contain: "http://localhost:10000/myContext/myServlet/foo/bar" client .post("http://localhost:10000/foo", uri) .run();

      See Also:
      Parameters:
      value - The new value for this property.
      Cannot be null.
      Returns:
      This object.
    • uriRelativity

      Serializer configuration property:  URI relativity.

      Defines what relative URIs are relative to when serializing any of the following:

      • URI
      • URL
      • Properties and classes annotated with @Uri

      See uriContext(UriContext) for examples.

      See Also:
      Parameters:
      value - The new value for this property.
      The default is UriRelativity.RESOURCE
      Cannot be null.
      Returns:
      This object.
    • uriResolution

      Serializer configuration property:  URI resolution.

      Defines the resolution level for URIs when serializing any of the following:

      • URI
      • URL
      • Properties and classes annotated with @Uri

      See uriContext(UriContext) for examples.

      See Also:
      Parameters:
      value - The new value for this property.
      The default is UriResolution.NONE
      Cannot be null.
      Returns:
      This object.
    • urlEnc

      public SELF urlEnc()
      Convenience method for specifying URL-Encoding as the marshalling transmission media type.

      UrlEncodingSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      UrlEncodingParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "application/x-www-form-urlencoded" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "application/x-www-form-urlencoded" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(UrlEncodingSerializer.class).parser(UrlEncodingParser.class).

      Example:

      // Construct a client that uses URL-Encoded marshalling. RestClient client = RestClient.create().urlEnc().build();

      Returns:
      This object.
    • urlEncodingSerializer

      Returns the URL-encoding serializer sub-builder.
      Returns:
      The URL-encoding serializer sub-builder.
    • userTokenHandler

      public SELF userTokenHandler(UserTokenHandler userTokenHandler)
      Assigns UserTokenHandler instance.
      Notes:
      Parameters:
      userTokenHandler - New property value.
      Can be null (value will not be set, default behavior will be used).
      Returns:
      This object.
      See Also:
    • useSystemProperties

      Use system properties when creating and configuring default implementations.
      Notes:
      • The system properties Apache HttpClientBuilder reads for its own connection manager apply to both pools of the connection manager the default createConnectionManager() builds, as Apache applies them: with no sslContext or sslSocketFactory, https uses the JVM's default SSL socket factory (the javax.net.ssl.* trust and key stores); https.protocols and https.cipherSuites restrict the TLS versions and cipher suites (unless an sslSocketFactory is set); and unless http.keepAlive is false, http.maxConnections (default 5) limits the connections per route, and twice that in total, which makes the connection manager a pooling one. maxConnTotal(int) and maxConnPerRoute(int) win over that limit.
      • The proxy system properties apply too (see proxy(HttpHost)).
      Returns:
      This object.
      See Also:
    • useWhitespace

      public SELF useWhitespace()
      WriterSerializer configuration property:  Use whitespace.

      When enabled, whitespace is added to the output to improve readability.

      Example:

      // Create a REST client with JSON serializer with whitespace enabled. RestClient client = RestClient .create() .json() .useWhitespace() .build(); // A bean with a single property public class MyBean { public String foo = "bar"; } // Request body will contain: {\n\t"foo": "bar"\n\}\n client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • ws

      public SELF ws()
      WriterSerializer configuration property:  Use whitespace.

      When enabled, whitespace is added to the output to improve readability.

      Example:

      // Create a REST client with JSON serializer with whitespace enabled. RestClient client = RestClient .create() .json() .ws() .build(); // A bean with a single property public class MyBean { public String foo = "bar"; } // Request body will contain: {\n\t"foo": "bar"\n\}\n client .post("http://localhost:10000/foo", new MyBean()) .run();

      See Also:
      Returns:
      This object.
    • xml

      public SELF xml()
      Convenience method for specifying XML as the marshalling transmission media type.

      XmlSerializer will be used to serialize POJOs to request bodies unless overridden per request via RestRequest.serializer(Serializer).

      XmlParser will be used to parse POJOs from response bodies unless overridden per request via RestRequest.parser(Parser).

      Accept request header will be set to "text/xml" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Content-Type request header will be set to "text/xml" unless overridden via headers(), or per-request via RestRequest.header(Header).

      Can be combined with other marshaller setters such as json() to provide support for multiple languages.

      • When multiple languages are supported, the Accept and Content-Type headers control which marshallers are used, or uses the last-enabled language if the headers are not set.

      Identical to calling serializer(XmlSerializer.class).parser(XmlParser.class).

      Example:

      // Construct a client that uses XML marshalling. RestClient client = RestClient.create().xml().build();

      Returns:
      This object.
    • createCallHandler

      Creates the creator for the rest call handler.

      Subclasses can override this method to provide their own implementation.

      The default behavior creates a bean instantiator initialized to return a BasicRestCallHandler.

      Returns:
      The creator for the rest call handler.
      See Also:
    • createConnectionManager

      Creates the HttpClientConnectionManager returned by createConnectionManager().

      Subclasses can override this method to provide their own connection manager.

      The default implementation returns a new PoolingHttpClientConnectionManager if pooled(), maxConnTotal(int), maxConnPerRoute(int) or a positive connectionTimeToLive was set, or the http.maxConnections limit of useSystemProperties() applies (unless http.keepAlive is false), or a new BasicHttpClientConnectionManager if not. It applies the sslContext, sslSocketFactory, sslHostnameVerifier, maxConnTotal and maxConnPerRoute settings, which Apache HttpClientBuilder ignores once a connection manager is set. It also applies, to both pools, the other settings Apache HttpClientBuilder applies only to a connection manager it builds itself, whether made through this builder or directly on the HttpClientBuilder: publicSuffixMatcher (for the default hostname verifier), defaultSocketConfig, defaultConnectionConfig, connectionTimeToLive (which, like maxConnTotal and maxConnPerRoute, makes it a PoolingHttpClientConnectionManager) and the TLS and http.maxConnections system properties of useSystemProperties(). A DNS resolver set on the HttpClientBuilder is used for ordinary requests only: SSRF-guard-active @Remote calls always resolve through the SSRF pin. Each of these settings made through this builder also survives httpClientBuilder(HttpClientBuilder) replacing the HttpClientBuilder, and always wins over the same setting on the HttpClientBuilder, whichever was set last (unlike Apache's own last-write-wins). An SSL socket factory wins over any SSL context, wherever each was set. The HttpClientBuilder's settings are read from its fields (it has no getters); if they cannot be read, this method throws an IllegalStateException rather than ignore them.

      Each build() calls this method again, so a builder reused after build() gives every client its own connection manager (closing one client does not shut down another's). A connection manager supplied through connectionManager(HttpClientConnectionManager) is used as is by every client built.

      SSRF-guard-active @Remote calls do not use this connection manager: the default createHttpClient() pairs it with a second, dedicated one whose connections are all opened through the SSRF pin, so that a guarded call never reuses a connection an ordinary request opened. It can only do that for the instance this default implementation returns. If an override returns any other connection manager, the client refuses every SSRF-guard-active @Remote call (one without the allowPrivateUrls opt-in).

      The dedicated connection manager copies this one's settings before each guarded call, but it is a separate pool: limits such as maxTotal apply to each pool on its own, so a client that mixes ordinary and guarded calls can hold up to twice as many open connections.

      Example:

      // A Builder that provides it's own customized HttpClientConnectionManager. public class MyBuilder extends Builder { @Override protected HttpClientConnectionManager createConnectionManager() { return new PoolingHttpClientConnectionManager(); } } // Instantiate. RestClient client = new MyBuilder().build();

      Returns:
      The connection manager to use.
    • createFormData

      protected PartList createFormData()
      Creates the builder for the form data list.

      Subclasses can override this method to provide their own implementation.

      The default behavior creates an empty builder.

      Returns:
      The form data list builder.
      See Also:
    • createHeaderData

      Creates the builder for the header list.

      Subclasses can override this method to provide their own implementation.

      The default behavior creates an empty builder.

      Returns:
      The header list builder.
      See Also:
    • createHttpClient

      Creates an instance of an HttpClient to be used to handle all HTTP communications with the target server.

      This HTTP client is used when the HTTP client is not specified through one of the constructors or the httpClient(CloseableHttpClient) method.

      Subclasses can override this method to provide specially-configured HTTP clients to handle stuff such as SSL/TLS certificate handling, authentication, etc.

      The default implementation returns an instance of HttpClient using the client builder returned by createHttpClientBuilder().

      Notes:
      • SSRF-guard-active @Remote calls (ones without the allowPrivateUrls opt-in) are only sent through the client this default implementation builds, which it wires to the connection manager that pins them. The client refuses every such call if an override returns any other client (including a wrapper around the one it built), or after super.createHttpClient() sets an HttpProcessor on the HttpClientBuilder, adds a request interceptor with addInterceptorLast(...), or replaces its redirect strategy or request executor (make such changes before calling super), or if the builder is a subclass that overrides HttpClientBuilder.build() or one of its exec-chain methods (createMainExec, decorateMainExec, decorateProtocolExec), even an override that returns or decorates nothing but what super built. Ordinary requests are unaffected.
      Example:

      // A Builder that provides it's own customized HttpClient. public class MyBuilder extends Builder { @Override protected HttpClientBuilder createHttpClient() { return HttpClientBuilder.create().build(); } } // Instantiate. RestClient client = new MyBuilder().build();

      Returns:
      The HTTP client to use.
    • createHttpClientBuilder

      Creates an instance of an HttpClientBuilder to be used to create the HttpClient.

      Subclasses can override this method to provide their own client builder. The builder can also be specified using the httpClientBuilder(HttpClientBuilder) method.

      Example:

      // A Builder that provides it's own customized HttpClientBuilder. public class MyBuilder extends Builder { @Override protected HttpClientBuilder createHttpClientBuilder() { return HttpClientBuilder.create(); } } // Instantiate. RestClient client = new MyBuilder().build();

      Returns:
      The HTTP client builder to use to create the HTTP client.
    • createParsers

      Instantiates the parser group sub-builder.
      Returns:
      A new parser group sub-builder.
    • createPartParser

      Instantiates the part parser sub-builder.
      Returns:
      A new part parser sub-builder.
    • createPartSerializer

      Instantiates the part serializer sub-builder.
      Returns:
      A new part serializer sub-builder.
    • createPathData

      protected PartList createPathData()
      Creates the builder for the path data list.

      Subclasses can override this method to provide their own implementation.

      The default behavior creates an empty builder.

      Returns:
      The path data list builder.
      See Also:
    • createQueryData

      Creates the builder for the query data list.

      Subclasses can override this method to provide their own implementation.

      The default behavior creates an empty builder.

      Returns:
      The query data list builder.
      See Also:
    • createSerializers

      Instantiates the serializer group sub-builder.
      Returns:
      A new serializer group sub-builder.
    • createUrlEncodingSerializer

      Instantiates the URL-encoding serializer sub-builder.
      Returns:
      A new URL-encoding serializer sub-builder.