Class RestClient.Builder<SELF extends RestClient.Builder<SELF>>
- Direct Known Subclasses:
MockRestClient.Builder,RestClient.DefaultBuilder
- Enclosing class:
- RestClient
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionAppends anAccept header on this request.acceptCharset(String value) Sets the value for theAccept-Charset request header on all requests.Serializer configuration property: Add"_type" properties when needed.Adds this protocol interceptor to the head of the protocol processing list.Adds this protocol interceptor to the head of the protocol processing list.Adds this protocol interceptor to the tail of the protocol processing list.Adds this protocol interceptor to the tail of the protocol processing list.Serializer configuration property: Add type attribute to root nodes.allowAddressRanges(String... value) Allows this client's SSRF-guarded@Remote/@Urlcalls to reach hosts inside the given special-purpose address ranges that the default policy denies (seeorg.apache.juneau.http.remote.RemoteUrlPolicy).allowPrivateUrls(boolean value) Opts every@Remote/@Urlcall made through this client out of the default deny-private SSRF guardrail (seeorg.apache.juneau.http.remote.RemoteUrlPolicy), for local-dev/intranet targets that are intentionally private.backoffManager(BackoffManager backoffManager) AssignsBackoffManagerinstance.Set up this client to use BASIC auth.bson()Convenience method for specifying BSON as the marshalling transmission media type.build()Build the object.Returns the creator for the rest call handler.callHandler(Class<? extends RestCallHandler> value) REST call handler class.clientVersion(String value) Sets the client version by setting the value for the"Client-Version" header.connectionBackoffStrategy(ConnectionBackoffStrategy connectionBackoffStrategy) AssignsConnectionBackoffStrategyinstance.AssignsHttpClientConnectionManagerinstance.connectionManagerShared(boolean shared) Defines the connection manager is to be shared by multiple client instances.connectionReuseStrategy(ConnectionReuseStrategy reuseStrategy) AssignsConnectionReuseStrategyinstance.connectionTimeToLive(long connTimeToLive, TimeUnit connTimeToLiveTimeUnit) Sets maximum time to live for persistent connections.console(PrintStream value) Console print streamcontentDecoderRegistry(Map<String, InputStreamFactory> contentDecoderMap) Assigns a map ofInputStreamFactoriesto be used for automatic content decompression.contentType(String value) Sets the value for theContent-Type request header on all requests.copy()Copy creator.protected BeanInstantiator.Builder<RestCallHandler>Creates the creator for the rest call handler.protected HttpClientConnectionManagerCreates theHttpClientConnectionManagerreturned bycreateConnectionManager().protected PartListCreates the builder for the form data list.protected HeaderListCreates the builder for the header list.protected CloseableHttpClientCreates an instance of anHttpClientto be used to handle all HTTP communications with the target server.protected HttpClientBuilderCreates an instance of anHttpClientBuilderto be used to create theHttpClient.protected ParserSet.BuilderInstantiates the parser group sub-builder.protected HttpPartParser.CreatorInstantiates the part parser sub-builder.protected HttpPartSerializer.CreatorInstantiates the part serializer sub-builder.protected PartListCreates the builder for the path data list.protected PartListCreates the builder for the query data list.protected SerializerSet.BuilderInstantiates the serializer group sub-builder.protected UrlEncodingSerializer.BuilderInstantiates the URL-encoding serializer sub-builder.debug()Sets the value for theDebug request header on all requests.debugOutputLines(int value) Parser configuration property: Debug output lines.defaultAuthSchemeRegistry(Lookup<AuthSchemeProvider> authSchemeRegistry) Assigns defaultAuthSchemeregistry which will be used for request execution if not explicitly set in the client execution context.Assigns defaultConnectionConfig.defaultCookieSpecRegistry(Lookup<CookieSpecProvider> cookieSpecRegistry) Assigns defaultCookieSpecregistry which will be used for request execution if not explicitly set in the client execution context.defaultCookieStore(CookieStore cookieStore) Assigns defaultCookieStoreinstance which will be used for request execution if not explicitly set in the client execution context.defaultCredentialsProvider(CredentialsProvider credentialsProvider) Assigns defaultCredentialsProviderinstance which will be used for request execution if not explicitly set in the client execution context.defaultRequestConfig(RequestConfig config) Assigns defaultRequestConfiginstance which will be used for request execution if not explicitly set in the client execution context.defaultSocketConfig(SocketConfig config) Assigns defaultSocketConfig.RestClient configuration property: Enable leak detection.BeanTraverse configuration property: Automatically detect POJO recursions.Disables authentication scheme caching.Disables automatic request recovery and re-execution.Disables connection state tracking.Disables automatic content decompression.Disables state (cookie) management.Disables automatic redirect handling.errorCodes(Predicate<Integer> value) Errors codes predicate.Makes this instance ofHttpClientproactively evict expired connections from the connection pool using a background thread.evictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUnit) Makes this instance ofHttpClientproactively evict idle connections from the connection pool using a background thread.executorService(ExecutorService executorService, boolean shutdownOnClose) RestClient configuration property: Executor service.final PartListformData()Returns the builder for the list of form data parameters that get applied to all requests created by this builder.Appends a form-data parameter to all request bodies.Appends a form-data parameter with a dynamic value to all request bodies.formData(NameValuePair... parts) Appends multiple form-data parameters to the request bodies of all URL-encoded form posts.formDataDefault(NameValuePair... parts) Sets default form-data parameter values.Returns the root URI defined for this client.Returns the root URL supplier set on this builder.Appends a header to all requests.Appends a header to all requests using a dynamic value.final HeaderListheaders()Returns the builder for the list of headers that get applied to all requests created by this builder.Appends multiple headers to all requests.headersDefault(Header... parts) Sets default header values.html()Convenience method for specifying HTML as the marshalling transmission media type.htmlDoc()Convenience method for specifying HTML DOC as the marshalling transmission media type.Convenience method for specifying Stripped HTML DOC as the marshalling transmission media type.httpClient(CloseableHttpClient value) Sets theHttpClientto be used to handle all HTTP communications with the target server.final HttpClientBuilderReturns the HTTP client builder.httpProcessor(HttpProcessor httpprocessor) AssignsHttpProcessorinstance.Ignore errors.BeanTraverse configuration property: Ignore recursion errors.initialDepth(int value) BeanTraverse configuration property: Initial depth.interceptors(Class<?>... values) RestClient configuration property: Call interceptors.interceptors(Object... value) Call interceptors.jcs()Convenience method for specifying JCS (JSON Canonicalization Scheme, RFC 8785) as the marshalling transmission media type.json()Convenience method for specifying JSON as the marshalling transmission media type.json5()Convenience method for specifying Simplified JSON as the marshalling transmission media type.keepAliveStrategy(ConnectionKeepAliveStrategy keepAliveStrategy) AssignsConnectionKeepAliveStrategyinstance.RestClient configuration property: Keep HttpClient open.Serializer configuration property: Don't trim null bean property values.Logger.logRequests(DetailLevel detail, Level level, BiPredicate<RestRequest, RestResponse> test) Log requests.Log to console.marshaller(Marshaller value) RestClient configuration property: Marshallermarshallers(Marshaller... value) RestClient configuration property: MarshallsmaxConnPerRoute(int maxConnPerRoute) Assigns maximum connection per route value.maxConnTotal(int maxConnTotal) Assigns maximum total connection value.maxDepth(int value) BeanTraverse configuration property: Max serialization depth.maxIndent(int value) WriterSerializer configuration property: Maximum indentation.Appends theAccept andContent-Type headers on all requests made by this client.Appends theAccept andContent-Type headers on all requests made by this client.msgPack()Convenience method for specifying MessagePack as the marshalling transmission media type.noTrace()When called,No-Trace: true is added to requests.OpenApiCommon configuration property: Default collection format for HTTP parts.oapiFormat(HttpPartFormat value) OpenApiCommon configuration property: Default OpenAPI format for HTTP parts.openApi()Convenience method for specifying OpenAPI as the marshalling transmission media type.paramFormat(ParamFormat value) UonSerializer configuration property: Parameter format.UonSerializer configuration property: Parameter format.Parser.Parser.final ParserSet.Builderparsers()Returns the parser group sub-builder.Parsers.Parsers.parserSessionOptionsHeader(String json5) Sets a default request header with parser session options (JSON5 map) for all requests.parserSessionOptionsHeader(Map<String, ?> properties) Convenience forparserSessionOptionsHeader(String)using a map serialized with JSON5.Sets a default query parameter with parser session options (UON map) for all requests.parserSessionOptionsQueryDefault(Map<String, ?> properties) Convenience forparserSessionOptionsQueryDefault(String)usingUon.of(Object).final HttpPartParser.CreatorReturns the part parser sub-builder.partParser(Class<? extends HttpPartParser> value) Part parser.partParser(HttpPartParser value) Part parser.Returns the part serializer sub-builder.partSerializer(Class<? extends HttpPartSerializer> value) Part serializer.partSerializer(HttpPartSerializer value) Part serializer.final PartListpathData()Returns the builder for the list of path data parameters that get applied to all requests created by this builder.Appends a path parameter to all request bodies.Sets a path parameter with a dynamic value to all request bodies.pathData(NameValuePair... parts) Sets multiple path parameters on all requests.pathDataDefault(NameValuePair... parts) Sets default path parameter values.Convenience method for specifying Plain Text as the marshalling transmission media type.pooled()When called, thecreateConnectionManager()method will return aPoolingHttpClientConnectionManagerinstead of aBasicHttpClientConnectionManager.Assigns default proxy value.proxyAuthenticationStrategy(AuthenticationStrategy proxyAuthStrategy) AssignsAuthenticationStrategyinstance for proxy authentication.publicSuffixMatcher(PublicSuffixMatcher publicSuffixMatcher) Assigns file containing public suffix matcher.final PartListReturns the builder for the list of query parameters that get applied to all requests created by this builder.Appends a query parameter to the URI.Appends a query parameter with a dynamic value to the URI.queryData(NameValuePair... parts) Appends multiple query parameters to the URI of all requests.queryDataDefault(NameValuePair... parts) Sets default query parameter values.quoteChar(char value) WriterSerializer configuration property: Quote character.redirectStrategy(RedirectStrategy redirectStrategy) AssignsRedirectStrategyinstance.requestExecutor(HttpRequestExecutor requestExec) AssignsHttpRequestExecutorinstance.retryHandler(HttpRequestRetryHandler retryHandler) AssignsHttpRequestRetryHandlerinstance.RestClient configuration property: Root URI.Sets the root URL using a supplier, allowing the URL to be computed dynamically at request time.routePlanner(HttpRoutePlanner routePlanner) AssignsHttpRoutePlannerinstance.schemePortResolver(SchemePortResolver schemePortResolver) AssignsSchemePortResolverinstance.serializer(Class<? extends Serializer> value) Serializer.serializer(Serializer value) Serializer.final SerializerSet.BuilderReturns the serializer group sub-builder.serializers(Class<? extends Serializer>... value) Serializers.serializers(Serializer... value) Serializers.Sets a default request header with serializer session options (JSON5 map) for all requests.serializerSessionOptionsHeader(Map<String, ?> properties) Convenience forserializerSessionOptionsHeader(String)using a map serialized with JSON5.Sets a default query parameter with serializer session options (UON map) for all requests.serializerSessionOptionsQueryDefault(Map<String, ?> properties) Convenience forserializerSessionOptionsQueryDefault(String)usingUon.of(Object).serviceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy serviceUnavailStrategy) AssignsServiceUnavailableRetryStrategyinstance.Skip empty form data.skipEmptyFormData(boolean value) Skip empty form data.Skip empty header data.skipEmptyHeaderData(boolean value) Skip empty header data.Skip empty query data.skipEmptyQueryData(boolean value) Skip empty query data.Serializer configuration property: Sort arrays and collections alphabetically.sortMaps()Serializer configuration property: Sort maps alphabetically.sq()WriterSerializer configuration property: Quote character.sslContext(SSLContext sslContext) AssignsSSLContextinstance.sslHostnameVerifier(HostnameVerifier hostnameVerifier) AssignsHostnameVerifierinstance.sslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) AssignsLayeredConnectionSocketFactoryinstance.targetAuthenticationStrategy(AuthenticationStrategy targetAuthStrategy) AssignsAuthenticationStrategyinstance for target host authentication.Serializer configuration property: Trim empty lists and arrays.Serializer configuration property: Trim empty maps.Parser configuration property: Trim parsed strings.Serializer configuration property: Trim strings.Convenience method for specifying all available transmission types.uon()Convenience method for specifying UON as the marshalling transmission media type.uriContext(UriContext value) Serializer configuration property: URI context bean.uriRelativity(UriRelativity value) Serializer configuration property: URI relativity.uriResolution(UriResolution value) Serializer configuration property: URI resolution.urlEnc()Convenience method for specifying URL-Encoding as the marshalling transmission media type.Returns the URL-encoding serializer sub-builder.userTokenHandler(UserTokenHandler userTokenHandler) AssignsUserTokenHandlerinstance.Use system properties when creating and configuring default implementations.WriterSerializer configuration property: Use whitespace.ws()WriterSerializer configuration property: Use whitespace.xml()Convenience method for specifying XML as the marshalling transmission media type.Methods inherited from class org.apache.juneau.marshall.MarshallingContextable.Builder
activeView, annotations, beanClassVisibility, beanConstructorVisibility, beanDictionary, beanFieldVisibility, beanInterceptor, beanMapPutReturnsOldValue, beanMethodVisibility, beanProperties, beanProperties, beanProperties, beanPropertiesExcludes, beanPropertiesExcludes, beanPropertiesExcludes, beanPropertiesReadOnly, beanPropertiesReadOnly, beanPropertiesReadOnly, beanPropertiesWriteOnly, beanPropertiesWriteOnly, beanPropertiesWriteOnly, beansRequireDefaultConstructor, beansRequireSerializable, beansRequireSettersForGetters, bigNumberFormat, binaryFormat, bitSetFormat, booleanFormat, calendarFormat, classFormat, classLoader, currencyFormat, dateFormat, dictionaryOn, disableBeansRequireSomeProperties, disableDefaultViewInclusion, disableIgnoreMissingSetters, disableIgnoreTransientFields, disableIgnoreUnknownNullBeanProperties, disableInterfaceProxies, durationFormat, enumFormat, example, example, findFluentSetters, findFluentSetters, floatFormat, hashKey, ignoreInvocationExceptionsOnGetters, ignoreInvocationExceptionsOnSetters, ignoreUnknownBeanProperties, ignoreUnknownEnumValues, implClass, implClasses, interfaceClass, interfaces, locale, localeFormat, marshallingContext, marshallingContext, marshallingContext, marshallingContext, notBeanClasses, notBeanPackages, periodFormat, propertyNamer, propertyNamer, recordComponentOrder, stopClass, swap, swap, swaps, swaps, temporalFormat, timeZone, timeZoneFormat, typeName, typePropertyName, typePropertyName, unsortedProperties, unsortedProperties, useJavaBeanIntrospector, uuidFormat, validateSchema, validateSchemaMethods inherited from class org.apache.juneau.marshall.Context.Builder
annotations, apply, applyAnnotations, applyAnnotations, asSubtype, build, cache, canApply, copyOrNull, debug, getApplied, getType, impl, isDebug, registerBuilders, self, type
-
Constructor Details
-
Builder
protected Builder()Constructor.
-
-
Method Details
-
accept
Appends anAccept header on this request.This is a shortcut for calling
headerData().append(Accept. .of (value ))- Parameters:
value- The new header value.
Can benull (no Accept header will be added).- Returns:
- This object.
- See Also:
-
acceptCharset
Sets the value for theAccept-Charset request header on all requests.This is a shortcut for calling
headerData().append(AcceptCharset. .of (value ))- Parameters:
value- The new header value.
Can benull (no Accept-Charset header will be added).- Returns:
- This object.
- See Also:
-
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 aMap<String,Object> field where the bean class cannot be determined from the type of the values.Note the differences between the following settings:
addRootType()- Affects whether'_type' is added to root node.addBeanTypes()- Affects whether'_type' is added to any nodes.
Example:
// Create a JSON client that adds _type to nodes in the request body. RestClientclient = RestClient .create () .json() .addBeanTypes() .build();// Our map of beans to serialize. @Marshalled (typeName="mybean" )public class MyBean {public Stringfoo ="bar" ; } AMapmap = 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:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorFirst
Adds this protocol interceptor to the head of the protocol processing list.Notes:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorLast
Adds this protocol interceptor to the tail of the protocol processing list.Notes:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorLast
Adds this protocol interceptor to the tail of the protocol processing list.Notes:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
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:
addRootType()- Affects whether'_type' is added to root node.addBeanTypes()- Affects whether'_type' is added to any nodes.
Example:
// Create a JSON client that adds _type to root node. RestClientclient = RestClient .create () .json() .addRootType() .build();// Our bean to serialize. @Marshalled (typeName="mybean" )public class MyBean {public Stringfoo ="bar" ; }// Request body will contain: {"_type":"mybean","foo":"bar"} client .post("http://localhost:10000/foo" ,new MyBean()) .run();See Also:
- Returns:
- This object.
-
backoffManager
AssignsBackoffManagerinstance.- Parameters:
backoffManager- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
basicAuth
Set up this client to use BASIC auth.Example:
// Construct a client that uses BASIC authentication. RestClientclient = RestClient .create () .basicAuth("http://localhost" , 80,"me" ,"mypassword" ) .build();- Parameters:
host- The auth scope hostname.
Can benull (will use"*" as the hostname).port- The auth scope port.user- The username.
Can benull (will use empty string).pw- The password.
Can benull (will use empty string).- Returns:
- This object.
-
build
Description copied from class:Context.BuilderBuild the object.- Overrides:
buildin classContext.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 MyRestCallHandlerimplements RestCallHandler {@Override public HttpResponse run(HttpHosttarget , HttpRequestrequest , HttpContextcontext )throws IOException {// Custom handle requests. } } RestClientclient = RestClient .create () .callHandler(MyRestCallHandler.class ) .build();Notes:
- The SSRF guard of
@Remotecalls travels on the request'sHttpContext, and a custom handler may copy the request, or send it with another context, without it. So a client with any handler other thanBasicRestCallHandleritself, or with aBasicRestCallHandlerbound to a different client (throughimpl(...)), refuses every SSRF-guard-active@Remotecall (one without theallowPrivateUrlsopt-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 eitherexecute(...)overload it dispatches to refuses SSRF-guard-active@Remotecalls too. -
Use
BeanInstantiator.Builderimpl(Object) to specify an already instantiated instance. -
Use
BeanInstantiator.Buildertype(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 (includingRestClientitself).
See Also:
- Returns:
- The instantiator for the rest call handler.
- The SSRF guard of
-
callHandler
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 benull .- Returns:
- This object.
- See Also:
-
clientVersion
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 benull (no Client-Version header will be added).- Returns:
- This object.
- See Also:
-
connectionBackoffStrategy
AssignsConnectionBackoffStrategyinstance.- Parameters:
connectionBackoffStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
connectionManager
AssignsHttpClientConnectionManagerinstance.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
@Remotecall (one without theallowPrivateUrlsopt-in). Ordinary requests are unaffected.
- Parameters:
value- New property value.
Can benull (value will not be set, a default connection manager will be created).- Returns:
- This object.
- See Also:
- 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
-
connectionReuseStrategy
AssignsConnectionReuseStrategyinstance.- Parameters:
reuseStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
connectionTimeToLive
Sets maximum time to live for persistent connections.Notes:
- It is applied to both pools of the connection manager the default
createConnectionManager()builds. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager(). - A positive value makes that connection manager a
PoolingHttpClientConnectionManager, aspooled()does:BasicHttpClientConnectionManagerhas no time-to-live.
- Parameters:
connTimeToLive- New property value.connTimeToLiveTimeUnit- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- It is applied to both pools of the connection manager the default
-
console
Console print streamAllows you to redirect the console output to a different print stream.
- Parameters:
value- The new value for this setting.
Can benull (defaults toSystem.err ).- Returns:
- This object.
-
contentDecoderRegistry
Assigns a map ofInputStreamFactoriesto be used for automatic content decompression.- Parameters:
contentDecoderMap- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
contentType
Sets the value for theContent-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 benull (no Content-Type header will be added).- Returns:
- This object.
- See Also:
-
copy
Description copied from class:Context.BuilderCopy creator.- Specified by:
copyin classMarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>- Returns:
- A new mutable copy of this builder.
-
debug
Sets the value for theDebug request header on all requests.This is a shortcut for calling
headerData().append(Debug. .of (value ))- Overrides:
debugin classMarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>- Returns:
- This object.
- See Also:
-
debugOutputLines
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. RestClientclient = 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 (RestCallExceptione ) { 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 is5 .- Returns:
- This object.
-
defaultAuthSchemeRegistry
Assigns defaultAuthSchemeregistry which will be used for request execution if not explicitly set in the client execution context.- Parameters:
authSchemeRegistry- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultConnectionConfig
Assigns defaultConnectionConfig.Notes:
- It is applied to both pools of the connection manager the default
createConnectionManager()builds. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager().
- Parameters:
config- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- It is applied to both pools of the connection manager the default
-
defaultCookieSpecRegistry
Assigns defaultCookieSpecregistry which will be used for request execution if not explicitly set in the client execution context.- Parameters:
cookieSpecRegistry- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultCookieStore
Assigns defaultCookieStoreinstance which will be used for request execution if not explicitly set in the client execution context.- Parameters:
cookieStore- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultCredentialsProvider
Assigns defaultCredentialsProviderinstance which will be used for request execution if not explicitly set in the client execution context.- Parameters:
credentialsProvider- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultRequestConfig
Assigns defaultRequestConfiginstance which will be used for request execution if not explicitly set in the client execution context.- Parameters:
config- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultSocketConfig
Assigns defaultSocketConfig.Notes:
- It is applied to both pools of the connection manager the default
createConnectionManager()builds. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager().
- Parameters:
config- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- It is applied to both pools of the connection manager the default
-
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 RestClientclient = 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
Opts every@Remote/@Urlcall made through this client out of the default deny-private SSRF guardrail (seeorg.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.allowPrivateUrlssystem property, and the@Remote/@RemoteOpallowPrivateUrlsannotation attribute: any one of the three opting in is sufficient. Thehttp/httpsscheme requirement is unaffected.- Parameters:
value-trueto allow private/loopback/link-local/metadata@Remotetargets. Defaultfalse.- Returns:
- This object.
-
allowAddressRanges
Allows this client's SSRF-guarded@Remote/@Urlcalls to reach hosts inside the given special-purpose address ranges that the default policy denies (seeorg.apache.juneau.http.remote.RemoteUrlPolicy).Same narrow semantics and validation as the JVM-wide
RestClient.allowAddressRangessystem property: each entry is a CIDR range or single address (parsed without DNS) that must lie inside192.0.0.0/24,198.18.0.0/15,224.0.0.0/4,240.0.0.0/4orff00::/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 anIllegalArgumentException.- Parameters:
value- The CIDR ranges or addresses to allow. Can benull 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 asMarshallingRecursionExceptionwith 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. RestClientclient = RestClient .create () .json() .detectRecursions() .build();// Create a POJO model with a recursive loop. public class A {public Objectf ; } Aa =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 (RestCallExceptione } {// Handle exception. }See Also:
- Returns:
- This object.
-
disableAuthCaching
Disables authentication scheme caching.Notes:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
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:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
disableCookieManagement
Disables state (cookie) management.Notes:
- This value can be overridden by the
httpProcessor(HttpProcessor)method.
- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
disableRedirectHandling
Disables automatic redirect handling.- Returns:
- This object.
- See Also:
-
errorCodes
Errors codes predicate.Defines a predicate to test for error codes.
Example:
// Create a client that considers any 300+ responses to be errors. RestClientclient = RestClient .create () .errorCodes(x ->x >=300) .build();- Parameters:
value- The new value for this setting.
The default value isx -> x >= 400.
Cannot benull .- Returns:
- This object.
-
evictExpiredConnections
Makes this instance ofHttpClientproactively 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
HttpClientis configured to use a shared connection manager. - This method may not be used when the instance of
HttpClientis created inside an EJB container.
- Returns:
- This object.
- See Also:
- One MUST explicitly close HttpClient with
-
evictIdleConnections
Makes this instance ofHttpClientproactively 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
HttpClientis configured to use a shared connection manager. - This method may not be used when the instance of
HttpClientis created inside an EJB container.
- Parameters:
maxIdleTime- New property value.maxIdleTimeUnit- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- One MUST explicitly close HttpClient with
-
executorService
RestClient configuration property: Executor service.Defines the executor service to use when calling future methods on the
RestRequestclass.This executor service is used to create
Futureobjects on the following methods:RestRequest.runFuture()RestRequest.completeFuture()ResponseContent.asFuture(Class)(and similar methods)
The default executor service is a single-threaded
ThreadPoolExecutorwith a 30 second timeout and a queue size of 10.Example:
// Create a client with a customized executor service. RestClientclient = 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. Stringbody =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. MyBeanbean =myBeanFuture .get();- Parameters:
executorService- The executor service.
Can benull (a default executor service will be created if needed).shutdownOnClose- CallExecutorService.shutdown()whenRestClient.close()is called.- Returns:
- This object.
-
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" )); RestClientclient =builder .build();The following convenience methods are also provided for updating the parameters:
- Returns:
- The form data list builder.
-
formData
Appends multiple form-data parameters to the request bodies of all URL-encoded form posts.Example:
import static org.apache.juneau.http.HttpParts.*; RestClientclient = 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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
formData
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 benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
formData
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 benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
formDataDefault
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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
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
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 benull .value- The header value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
header
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 benull .value- The header value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
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" )); RestClientclient =builder .build();The following convenience methods are also provided for updating the headers:
- Returns:
- The header list builder.
-
headers
Appends multiple headers to all requests.Example:
import static org.apache.juneau.http.HttpHeaders.*; RestClientclient = 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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
headersDefault
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 containnull 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 benull (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 benull (default is not set by this method).- Returns:
- This object.
-
serializerSessionOptionsHeader
Convenience forserializerSessionOptionsHeader(String)using a map serialized with JSON5.- Parameters:
properties- Property names and values for serializer session options.
Can benull (treated as an empty map).- Returns:
- This object.
-
parserSessionOptionsHeader
Convenience forparserSessionOptionsHeader(String)using a map serialized with JSON5.- Parameters:
properties- Property names and values for parser session options.
Can benull (treated as an empty map).- Returns:
- This object.
-
html
Convenience method for specifying HTML as the marshalling transmission media type.POJOs are converted to HTML without any sort of doc wrappers.
HtmlSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
HtmlParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().html().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
htmlDoc
Convenience method for specifying HTML DOC as the marshalling transmission media type.POJOs are converted to fully renderable HTML pages.
HtmlDocSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
HtmlParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().htmlDoc().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
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.HtmlStrippedDocSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
HtmlParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html+stripped" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html+stripped" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().htmlStrippedDoc().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
httpClient
Sets theHttpClientto 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. RestClientclient = RestClient .create () .httpClient(HttpClientBuilder.create ().build()) .build();- Parameters:
value- TheHttpClientto be used to handle all HTTP communications with the target server.
Can benull (a default client will be created).- Returns:
- This object.
-
httpClientBuilder
Returns the HTTP client builder.- Returns:
- The HTTP client builder.
-
httpClientBuilder
Sets theHttpClientBuilderthat will be used to create theHttpClientused byRestClient.This can be used to bypass the builder created by
createHttpClientBuilder()method.Example:
// Construct a client that uses a customized HttpClientBuilder. RestClientclient = RestClient .create () .httpClientBuilder(HttpClientBuilder.create ()) .build();Notes:
- The TLS and connection-pool settings Apache
HttpClientBuilderapplies only to a connection manager it builds itself (setSSLContext,setSSLSocketFactory,setSSLHostnameVerifier,setPublicSuffixMatcher,setMaxConnTotal,setMaxConnPerRoute,setConnectionTimeToLive,setDefaultSocketConfig,setDefaultConnectionConfig,setDnsResolveranduseSystemProperties) are read from the given builder and applied to the connection manager the defaultcreateConnectionManager()builds (see there). - These connection-manager settings, made through a method of this builder before this method is
called, are applied too, and win over the same setting on the given builder:
sslContext,sslSocketFactory,sslHostnameVerifier,publicSuffixMatcher(for the default hostname verifier only: its use for cookies is lost with the replaced builder),maxConnTotal,maxConnPerRoute,pooled,connectionTimeToLive,defaultSocketConfig,defaultConnectionConfigand the TLS andhttp.maxConnectionssystem properties ofuseSystemProperties(). Every other setting made through this builder before this method is called (interceptors, proxy, the rest ofuseSystemProperties(), and so on) was made on the replaced builder and is lost. - For these connection-manager settings, a value set through a method of this builder always wins
over the same setting on the
HttpClientBuilder, whichever was set last: unlike Apache's own last-write-wins, a laterhttpClientBuilder().setDefaultSocketConfig(...)(and so on) does not override an earlierdefaultSocketConfig(...). - As in Apache
HttpClientBuilder, an SSL socket factory wins over an SSL context wherever each was set: asetSSLSocketFactoryon the given builder wins over an earliersslContext. - A socket factory set with
setSSLSocketFactoryon the given builder is used for SSRF-guard-active@Remotecalls too, and must connect to exactly the address it is given (seesslSocketFactory(LayeredConnectionSocketFactory)). - A client built by an
HttpClientBuildersubclass that overrides (or inherits an override of)build(),createMainExec(...),decorateMainExec(...)ordecorateProtocolExec(...)refuses every SSRF-guard-active@Remotecall: the override may build the client around another connection manager or request executor.
- Parameters:
value- TheHttpClientBuilderthat will be used to create theHttpClientused byRestClient.
Can benull (a default builder will be created).- Returns:
- This object.
- The TLS and connection-pool settings Apache
-
httpProcessor
AssignsHttpProcessorinstance.Notes:
- The processor replaces all of the client's request interceptors, among them the ones that
enforce the SSRF guard and strip credentials on cross-origin redirects. So a client with one refuses every
SSRF-guard-active
@Remotecall (one without theallowPrivateUrlsopt-in). Add interceptors withHttpClientBuilder.addInterceptorLast(HttpRequestInterceptor)on theHttpClientBuilderinstead.
- Parameters:
httpprocessor- New property value.- Returns:
- This object.
- See Also:
- The processor replaces all of the client's request interceptors, among them the ones that
enforce the SSRF guard and strip credentials on cross-origin redirects. So a client with one refuses every
SSRF-guard-active
-
ignoreErrors
Ignore errors.When enabled, HTTP error response codes (e.g.
>=400 ) will not cause aRestCallExceptionto 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 istrue ...{A:{B:{C:
null }}}Notes:
- Checking for recursion can cause a small performance penalty.
Example:
// Create a JSON client that ignores recursions. RestClientclient = RestClient .create () .json() .ignoreRecursions() .build();// Create a POJO model with a recursive loop. public class A {public Objectf ; } Aa =new A();a .f =a ;// Produces request body "{f:null}" client .post("http://localhost:10000/foo" ,a ) .run();See Also:
- Returns:
- This object.
-
initialDepth
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. RestClientclient = RestClient .create () .json() .ws() .initialDepth(2) .build();// Our bean to serialize. public class MyBean {public Stringfoo =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 is0 .- Returns:
- This object.
-
interceptors
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 MyRestCallInterceptorimplements RestCallInterceptor {@Override public void onInit(RestRequestreq )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(RestRequestreq , RestResponseres )throws Exception {// Intercept immediately after an HTTP response has been received. }@Override public void onClose(RestRequestreq , RestResponseres )throws Exception {// Intercept when the response body is consumed. } }// Create a client with a customized interceptor. RestClientclient = RestClient .create () .interceptors(MyRestCallInterceptor.class ) .build();Notes:
- The
RestClient.onCallInit(RestRequest),RestClient.onCallConnect(RestRequest,RestResponse), andRestClient.onCallClose(RestRequest,RestResponse)methods can also be overridden to produce the same results.
- Parameters:
values- The values to add to this setting.
Can be implementations of any of the following:
Can containnull values (ignored).- Returns:
- This object.
- Throws:
Exception- If one or more interceptors could not be created.
- The
-
interceptors
Call interceptors.Adds an interceptor that gets called immediately after a connection is made.
Example:
// Create a client with a customized interceptor. RestClientclient = RestClient .create () .interceptors(new RestCallInterceptor() {@Override public void onInit(RestRequestreq )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(RestRequestreq , RestResponseres )throws Exception {// Intercept immediately after an HTTP response has been received. }@Override public void onClose(RestRequestreq , RestResponseres )throws Exception {// Intercept when the response body is consumed. } } ) .build();Notes:
- The
RestClient.onCallInit(RestRequest),RestClient.onCallConnect(RestRequest,RestResponse), andRestClient.onCallClose(RestRequest,RestResponse)methods can also be overridden to produce the same results.
- Parameters:
value- The values to add to this setting.
Can be implementations of any of the following:
Can containnull values (ignored).- Returns:
- This object.
- The
-
json
Convenience method for specifying JSON as the marshalling transmission media type.JsonSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
JsonParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/json" unless overridden viaheaders(), or per-request viaRestRequest.header(Header)}.Content-Type request header will be set to"application/json" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().json().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
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.
Json5Serializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Json5Parserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/json5" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"application/json5" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).A server that only handles JSON may reply
406 Not Acceptable or415 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 andContent-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. RestClientclient = RestClient.create ().json5().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
jcs
Convenience method for specifying JCS (JSON Canonicalization Scheme, RFC 8785) as the marshalling transmission media type.JcsSerializerwill be used to serialize POJOs to request bodies.JsonParserwill be used to parse POJOs from response bodies (JCS output is valid JSON).Accept andContent-Type will be set to"application/jcs+json" .Identical to calling
serializer(JcsSerializer. .class ).parser(JsonParser.class )- Returns:
- This object.
-
keepAliveStrategy
AssignsConnectionKeepAliveStrategyinstance.- Parameters:
keepAliveStrategy- New property value.
Can benull (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. RestClientclient = 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@Remotecalls (seecreateConnectionManager()) and the connection manager the defaultcreateConnectionManager()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.
- When combined with
-
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
Map s withnull values to be lost during parsing.
Example:
// Create a REST client with JSON serializer that serializes null properties. RestClientclient = RestClient .create () .json() .keepNullProperties() .build();// Our bean to serialize. public class MyBean {public Stringfoo =null ; }// Request body will contain: {foo:null} client .post("http://localhost:10000/foo" ,new MyBean()) .run();See Also:
- Returns:
- This object.
- Not enabling this setting will cause
-
logger
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. RestClientclient = 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 benull (defaults toLogger.getLogger(RestClient.class.getName()) ).- Returns:
- This object.
-
logRequests
public SELF logRequests(DetailLevel detail, Level level, BiPredicate<RestRequest, RestResponse> test) 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 thelogToConsole()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. Ifnull , always logs.- Returns:
- This object.
-
logToConsole
Log to console.Specifies to log messages to the console.
Example:
// Construct a client that logs messages to a special logger. RestClientclient = RestClient .create () .logToConsole() .logRequests(FULL ,INFO )// Level is ignored when logging to console. .build();- Returns:
- This object.
-
marshaller
RestClient configuration property: MarshallerShortcut for specifying the serializers and parsers using the serializer and parser defined in a marshaller.
Notes:
- When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g.
sortCollections()), parser property setters (e.g.MarshallingContextable.Builder.ignoreUnknownBeanProperties()), or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses Simplified-JSON transport using an existing marshaller. RestClientclient = RestClient .create () .marshaller(Json5.DEFAULT_READABLE ) .build();- Parameters:
value- The values to add to this setting.
Can benull (value will not be set, existing serializers and parsers will be kept).- Returns:
- This object.
- When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g.
-
marshallers
RestClient configuration property: MarshallsShortcut for specifying the serializers and parsers using the serializer and parser defined in a marshaller.
Notes:
- When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g.
sortCollections()), parser property setters (e.g.MarshallingContextable.Builder.ignoreUnknownBeanProperties()), or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses JSON and XML transport using existing marshalls. RestClientclient = RestClient .create () .marshaller(Json.DEFAULT_READABLE , Xml.DEFAULT_READABLE ) .build();- Parameters:
value- The values to add to this setting.
Can containnull values (ignored).- Returns:
- This object.
- When using this method that takes in a pre-instantiated serializers and parsers, the serializer property setters (e.g.
-
maxConnPerRoute
Assigns maximum connection per route value.Notes:
- A positive value is applied to the connection manager the default
createConnectionManager()builds, which is then always aPoolingHttpClientConnectionManager(as ifpooled()had been called), and to its internal pool for SSRF-guard-active@Remotecalls. - It has no effect on a connection manager supplied through
connectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager().
- Parameters:
maxConnPerRoute- New property value.- Returns:
- This object.
- See Also:
- A positive value is applied to the connection manager the default
-
maxConnTotal
Assigns maximum total connection value.Notes:
- A positive value is applied to the connection manager the default
createConnectionManager()builds, which is then always aPoolingHttpClientConnectionManager(as ifpooled()had been called), and to its internal pool for SSRF-guard-active@Remotecalls. Each pool applies the limit on its own (seecreateConnectionManager()). - It has no effect on a connection manager supplied through
connectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager().
- Parameters:
maxConnTotal- New property value.- Returns:
- This object.
- See Also:
- A positive value is applied to the connection manager the default
-
maxDepth
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. RestClientclient = RestClient .create () .json() .maxDepth(20) .build();See Also:
- Parameters:
value- The new value for this property.
The default is100 .- Returns:
- This object.
-
maxIndent
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. RestClientclient = RestClient .create () .json() .ws()// Enable whitespace .maxIndent(20) .build();See Also:
- Parameters:
value- The new value for this property.
The default is100 .- Returns:
- This object.
-
mediaType
Appends theAccept andContent-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:
mediaTypein classMarshallingContextable.Builder<SELF extends RestClient.Builder<SELF>>- Parameters:
value- The new header values.
Can benull (no Accept or Content-Type headers will be added).- Returns:
- This object.
- See Also:
-
mediaType
Appends theAccept andContent-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 benull (no Accept or Content-Type headers will be added).- Returns:
- This object.
- See Also:
-
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
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.
MsgPackSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
MsgPackParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/msgpack" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"application/msgpack" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().msgPack().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
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. RestClientclient = RestClient .create () .collectionFormat(CSV ) .build();// An arbitrary data structure. AListlist = 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();HttpPartCollectionFormatCSV- (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 isHttpPartCollectionFormat.NO_COLLECTION_FORMAT.
Cannot benull .- Returns:
- This object.
-
oapiFormat
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. RestClientclient = 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();HttpPartFormatUON- UON notation (e.g."'foo bar'" ).INT32- Signed 32 bits.INT64- Signed 64 bits.FLOAT- 32-bit floating point number.DOUBLE- 64-bit floating point number.BYTE- BASE-64 encoded characters.BINARY- Hexadecimal encoded octets (e.g."00FF" ).BINARY_SPACED- Spaced-separated hexadecimal encoded octets (e.g."00 FF" ).DATE- An RFC3339 full-date.DATE_TIME- An RFC3339 date-time.PASSWORD- Used to hint UIs the input needs to be obscured.NO_FORMAT- (default) Not specified.
See Also:
- Parameters:
value- The new value for this property.
The default value isHttpPartFormat.NO_FORMAT.
Cannot benull .- Returns:
- This object.
-
openApi
Convenience method for specifying OpenAPI as the marshalling transmission media type.OpenAPI is a language that allows serialization to formats that use
HttpPartSchemaobjects to describe their structure.OpenApiSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class. - Typically the
RestRequest.content(Object, HttpPartSchema)method will be used to specify the body of the request with the schema describing it's structure.
OpenApiParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class. - Typically the
ResponseContent.schema(HttpPartSchema)method will be used to specify the structure of the response body.
Accept request header will be set to"text/openapi" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/openapi" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().openApi().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
paramFormat
UonSerializer configuration property: Parameter format.Specifies the format of parameters when using the
UrlEncodingSerializerto 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. RestClientclient = RestClient .create () .urlEnc() .paramFormat(PLAINTEXT ) .build();// An arbitrary data structure. AMapmap = 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();ParamFormat.UON(default) - Use UON notation for parameters.ParamFormat.PLAINTEXT- Use plain text for parameters.
See Also:
- Parameters:
value- The new value for this property.
Cannot benull .- Returns:
- This object.
-
paramFormatPlain
UonSerializer configuration property: Parameter format.Specifies the format of parameters when using the
UrlEncodingSerializerto 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. RestClientclient = RestClient .create () .urlEnc() .build();// An arbitrary data structure. AMapmap = 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
Parser.Associates the specified
Parserwith the HTTP client.The parser is used to parse the HTTP response body into a POJO.
Notes:
- When using this method that takes in a class, the parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Example:
// Create a client that uses JSON transport for response bodies. RestClientclient = RestClient .create () .parser(JsonParser.class ) .build();- Parameters:
value- The new value for this setting.
The default value isJsonParser.DEFAULT.- Returns:
- This object.
- When using this method that takes in a class, the parser can be configured using any of the parser property setters (e.g.
-
parser
Parser.Associates the specified
Parserwith the HTTP client.The parser is used to parse the HTTP response body into a POJO.
Notes:
- When using this method that takes in a pre-instantiated parser, the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses a predefined JSON parser for response bodies. RestClientclient = RestClient .create () .parser(JsonParser.DEFAULT ) .build();- Parameters:
value- The new value for this setting.
The default value isJsonParser.DEFAULT.
Cannot benull .- Returns:
- This object.
- When using this method that takes in a pre-instantiated parser, the parser property setters (e.g.
-
parsers
Returns the parser group sub-builder.- Returns:
- The parser group sub-builder.
-
parsers
Parsers.Associates the specified
Parserswith 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 noAccept header is specified, the first parser in the list will be used.Notes:
- When using this method that takes in classes, the parsers can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Example:
// Create a client that uses JSON and XML transport for response bodies. RestClientclient = RestClient .create () .parser(JsonParser.class , XmlParser.class ) .build();- Parameters:
value- The new value for this setting.
The default value isJsonParser.DEFAULT.- Returns:
- This object.
- When using this method that takes in classes, the parsers can be configured using any of the parser property setters (e.g.
-
parsers
Parsers.Associates the specified
Parserswith 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 noAccept header is specified, the first parser in the list will be used.Notes:
- When using this method that takes in pre-instantiated parsers, the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses JSON and XML transport for response bodies. RestClientclient = RestClient .create () .parser(JsonParser.DEFAULT , XmlParser.DEFAULT ) .build();- Parameters:
value- The new value for this setting.
The default value isJsonParser.DEFAULT.- Returns:
- This object.
- When using this method that takes in pre-instantiated parsers, the parser property setters (e.g.
-
partParser
Returns the part parser sub-builder.- Returns:
- The part parser sub-builder.
-
partParser
Part parser.The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.
The default part parser is
OpenApiParserwhich allows for schema-driven marshalling.Example:
// Create a client that uses UON format by default for incoming HTTP parts. RestClientclient = RestClient .create () .partParser(UonParser.class ) .build();- Parameters:
value- The new value for this setting.
The default value isOpenApiParser.
Cannot benull .- Returns:
- This object.
-
partParser
Part parser.The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.
The default part parser is
OpenApiParserwhich allows for schema-driven marshalling.Example:
// Create a client that uses UON format by default for incoming HTTP parts. RestClientclient = RestClient .create () .partParser(UonParser.DEFAULT ) .build();- Parameters:
value- The new value for this setting.
The default value isOpenApiParser.
Cannot benull .- Returns:
- This object.
-
partSerializer
Returns the part serializer sub-builder.- Returns:
- The part serializer sub-builder.
-
partSerializer
Part serializer.The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.
The default part serializer is
OpenApiSerializerwhich allows for schema-driven marshalling.Example:
// Create a client that uses UON format by default for outgoing HTTP parts. RestClientclient = RestClient .create () .partSerializer(UonSerializer.class ) .build();- Parameters:
value- The new value for this setting.
The default value isOpenApiSerializer.
Cannot benull .- 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
OpenApiSerializerwhich allows for schema-driven marshalling.Example:
// Create a client that uses UON format by default for outgoing HTTP parts. RestClientclient = RestClient .create () .partSerializer(UonSerializer.DEFAULT ) .build();- Parameters:
value- The new value for this setting.
The default value isOpenApiSerializer.
Cannot benull .- Returns:
- This object.
-
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" )); RestClientclient =builder .build();The following convenience methods are also provided for updating the parameters:
- Returns:
- The form data list builder.
-
pathData
Sets multiple path parameters on all requests.Example:
import static org.apache.juneau.http.HttpParts.*; RestClientclient = 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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
pathData
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 benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
pathData
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 benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
pathDataDefault
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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
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...
PlainTextSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
PlainTextParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/plain" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/plain" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().plainText().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
pooled
When called, thecreateConnectionManager()method will return aPoolingHttpClientConnectionManagerinstead of aBasicHttpClientConnectionManager.Example:
// Construct a client that uses pooled connections. RestClientclient = RestClient .create () .pooled() .build();- Returns:
- This object.
-
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
@Remotecall (one without theallowPrivateUrlsopt-in) on a proxy route is refused. This applies to any proxy route, including one chosen by aroute planneror the proxy system properties (useSystemProperties()). Ordinary requests are unaffected.
- Parameters:
proxy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
proxyAuthenticationStrategy
AssignsAuthenticationStrategyinstance for proxy authentication.- Parameters:
proxyAuthStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
publicSuffixMatcher
Assigns file containing public suffix matcher.Notes:
- Instances of this class can be created with
PublicSuffixMatcherLoader. - It is used for cookies and, in both pools of the connection manager the default
createConnectionManager()builds, by the default hostname verifier (one is used unlesssslHostnameVerifier(HostnameVerifier)orsslSocketFactory(LayeredConnectionSocketFactory)is set).
- Parameters:
publicSuffixMatcher- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- Instances of this class can be created with
-
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" )); RestClientclient =builder .build();The following convenience methods are also provided for updating the parameters:
- Returns:
- The query data list builder.
-
queryData
Appends multiple query parameters to the URI of all requests.Example:
import static org.apache.juneau.http.HttpParts.*; RestClientclient = 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 containnull values (ignored).- Returns:
- This object.
- See Also:
-
queryData
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 benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
queryData
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 benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
queryDataDefault
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 containnull 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 benull (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 benull (default is not set by this method).- Returns:
- This object.
-
serializerSessionOptionsQueryDefault
Convenience forserializerSessionOptionsQueryDefault(String)usingUon.of(Object).- Parameters:
properties- Property names and values for serializer session options.
Can benull (treated as an empty map).- Returns:
- This object.
-
parserSessionOptionsQueryDefault
Convenience forparserSessionOptionsQueryDefault(String)usingUon.of(Object).- Parameters:
properties- Property names and values for parser session options.
Can benull (treated as an empty map).- Returns:
- This object.
-
quoteChar
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. RestClientclient = RestClient .create () .json() .quoteChar('\'' ) .build();// A bean with a single property public class MyBean {public Stringfoo ="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
AssignsRedirectStrategyinstance.Notes:
- This value can be overridden by the
disableRedirectHandling()method.
- Parameters:
redirectStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
requestExecutor
AssignsHttpRequestExecutorinstance.- Parameters:
requestExec- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
retryHandler
AssignsHttpRequestRetryHandlerinstance.Notes:
- This value can be overridden by the
disableAutomaticRetries()method.
- Parameters:
retryHandler- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
rootUrl
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 aURL,URI, or an absolute URI string.Example:
// Create a client that uses UON format by default for HTTP parts. RestClientclient = RestClient .create () .rootUrl("http://localhost:10000/foo" ) .build(); Barbar =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 aString but you can also pass inURI andURL objects as well.
Can benull (no root URL will be set).- Returns:
- This object.
-
rootUrl
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
AtomicReferencewhen you need to point the client at a different host at any time:AtomicReference<String>
urlRef =new AtomicReference<>("https://host1" ); RestClientclient = RestClient.create ().rootUrl(urlRef ::get).build();// Switch to a different host at runtime. urlRef .set("https://host2" ); -
Refreshable cached value — Use
Memoizer(viaSuppliers.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" )); RestClientclient = 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 benull (no root URL will be set).- Returns:
- This object.
-
Swappable reference — Use an
-
routePlanner
AssignsHttpRoutePlannerinstance.- Parameters:
routePlanner- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
schemePortResolver
AssignsSchemePortResolverinstance.- Parameters:
schemePortResolver- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
serializer
Serializer.Associates the specified
Serializerwith the HTTP client.The serializer is used to serialize POJOs into the HTTP request body.
Notes:
- When using this method that takes in a class, the serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Example:
// Create a client that uses JSON transport for request bodies. RestClientclient = RestClient .create () .serializer(JsonSerializer.class ) .sortCollections()// Sort any collections being serialized. .build();- Parameters:
value- The new value for this setting.
The default isJsonSerializer.- Returns:
- This object.
- When using this method that takes in a class, the serializer can be configured using any of the serializer property setters (e.g.
-
serializer
Serializer.Associates the specified
Serializerwith the HTTP client.The serializer is used to serialize POJOs into the HTTP request body.
Notes:
- When using this method that takes in a pre-instantiated serializer, the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses a predefined JSON serializer request bodies. RestClientclient = RestClient .create () .serializer(JsonSerializer.DEFAULT_READABLE ) .build();- Parameters:
value- The new value for this setting.
The default isJsonSerializer.
Cannot benull .- Returns:
- This object.
- When using this method that takes in a pre-instantiated serializer, the serializer property setters (e.g.
-
serializers
Returns the serializer group sub-builder.- Returns:
- The serializer group sub-builder.
-
serializers
Serializers.Associates the specified
Serializerswith 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 noContent-Type header is specified, the first serializer in the list will be used.Notes:
- When using this method that takes in classes, the serializers can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Example:
// Create a client that uses JSON and XML transport for request bodies. RestClientclient = RestClient .create () .serializers(JsonSerializer.class , XmlSerializer.class ) .sortCollections()// Sort any collections being serialized. .build();- Parameters:
value- The new value for this setting.
The default isJsonSerializer.- Returns:
- This object.
- When using this method that takes in classes, the serializers can be configured using any of the serializer property setters (e.g.
-
serializers
Serializers.Associates the specified
Serializerswith 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 noContent-Type header is specified, the first serializer in the list will be used.Notes:
- When using this method that takes in a pre-instantiated serializers, the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class have no effect.
Example:
// Create a client that uses predefined JSON and XML serializers for request bodies. RestClientclient = RestClient .create () .serializers(JsonSerializer.DEFAULT_READABLE , XmlSerializer.DEFAULT_READABLE ) .build();- Parameters:
value- The new value for this setting.
The default isJsonSerializer.- Returns:
- This object.
- When using this method that takes in a pre-instantiated serializers, the serializer property setters (e.g.
-
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
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 isfalse .- 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
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 isfalse .- 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
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 isfalse .- 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. RestClientclient = 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
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. RestClientclient = RestClient .create () .json() .sortMaps() .build();// An unsorted map. AMapmap = 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
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. RestClientclient = RestClient .create () .json() .sq() .build();// A bean with a single property public class MyBean {public Stringfoo ="bar" ; }// Request body will contain: {'foo':'bar'} client .post("http://localhost:10000/foo" ,new MyBean()) .run();See Also:
- Returns:
- This object.
-
sslContext
AssignsSSLContextinstance.The context (for example one initialized with a custom trust store) is used for
httpsconnections, with thehostname verifierif one is set, or the default one.Notes:
- It is applied to the connection manager the default
createConnectionManager()builds, for both ordinary requests and the internal pool for SSRF-guard-active@Remotecalls. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager(), which carries its own socket factories. - An
SSL socket factorytakes precedence over this value, including one set withsetSSLSocketFactoryon a builder passed tohttpClientBuilder(HttpClientBuilder)after this value was set (as in ApacheHttpClientBuilder).
- Parameters:
sslContext- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- It is applied to the connection manager the default
-
sslHostnameVerifier
AssignsHostnameVerifierinstance.Notes:
- It is applied to the connection manager the default
createConnectionManager()builds, for both ordinary requests and the internal pool for SSRF-guard-active@Remotecalls. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager(), which carries its own socket factories. - An
SSL socket factorytakes precedence over this value, including one set withsetSSLSocketFactoryon a builder passed tohttpClientBuilder(HttpClientBuilder)after this value was set (as in ApacheHttpClientBuilder).
- Parameters:
hostnameVerifier- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- It is applied to the connection manager the default
-
sslSocketFactory
AssignsLayeredConnectionSocketFactoryinstance.The factory is used for
httpsconnections, in place of one built from theSSL contextandhostname verifier.Notes:
- It is applied to the connection manager the default
createConnectionManager()builds, for both ordinary requests and the internal pool for SSRF-guard-active@Remotecalls. It has no effect on a connection manager supplied throughconnectionManager(HttpClientConnectionManager)or an overriddencreateConnectionManager(), which carries its own socket factories. - For SSRF-guard-active
@Remotecalls, the factory is given the address the SSRF pin has already checked (theremoteAddressofconnectSocket). It must connect to exactly that address: a factory that ignores it and connects by host name (resolving the name again) bypasses the pin. The same holds for a factory set withsetSSLSocketFactoryon a builder passed tohttpClientBuilder(HttpClientBuilder).
- Parameters:
sslSocketFactory- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- It is applied to the connection manager the default
-
targetAuthenticationStrategy
AssignsAuthenticationStrategyinstance for target host authentication.- Parameters:
targetAuthStrategy- New property value.
Can benull (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. WriterSerializerserializer = 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
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. RestClientclient = RestClient .create () .json() .trimEmptyMaps() .build();// A bean with a field with an empty map. public class MyBean {public AMapfoo = 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. RestClientclient = 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. RestClientclient = RestClient .create () .json() .trimStrings() .build();// A map with space-padded keys/values AMapmap = AMap.of (" foo " ," bar " );// Request body will contain: {"foo":"bar"} client .post("http://localhost:10000/foo" ,map ) .run();See Also:
- Returns:
- This object.
-
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).- The serializers can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
All basic Juneau parsers will be used to parse POJOs from response bodies unless overridden per request via
RestRequest.parser(Parser).- The parsers can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header must be set viaheaders(), or per-request viaRestRequest.header(Header)in order for the correct parser to be selected.Content-Type request header must be set viaheaders(), or per-request viaRestRequest.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. RestClientclient = RestClient.create ().universal().build();- Returns:
- This object.
- The serializers can be configured using any of the serializer property setters (e.g.
-
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.
UonSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
UonParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/uon" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/uon" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().uon().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
uriContext
Serializer configuration property: URI context bean.Bean used for resolution of URIs to absolute or root-relative form.
Example:
// Our URI contextual information. Stringauthority ="http://localhost:10000" ; StringcontextRoot ="/myContext" ; StringservletPath ="/myServlet" ; StringpathInfo ="/foo" ;// Create a UriContext object. UriContexturiContext =new UriContext(authority ,contextRoot ,servletPath ,pathInfo );// Create a REST client with JSON serializer and associate our context. RestClientclient = 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 URIuri =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 benull .- Returns:
- This object.
-
uriRelativity
Serializer configuration property: URI relativity.Defines what relative URIs are relative to when serializing any of the following:
See
uriContext(UriContext)for examples.UriRelativity.RESOURCE- Relative URIs should be considered relative to the servlet URI.UriRelativity.PATH_INFO- Relative URIs should be considered relative to the request URI.
See Also:
- Parameters:
value- The new value for this property.
The default isUriRelativity.RESOURCE
Cannot benull .- Returns:
- This object.
-
uriResolution
Serializer configuration property: URI resolution.Defines the resolution level for URIs when serializing any of the following:
See
uriContext(UriContext)for examples.UriResolution.ABSOLUTE- Resolve to an absolute URI (e.g."http://host:port/context-root/servlet-path/path-info" ).UriResolution.ROOT_RELATIVE- Resolve to a root-relative URI (e.g."/context-root/servlet-path/path-info" ).UriResolution.NONE- Don't do any URI resolution.
See Also:
- Parameters:
value- The new value for this property.
The default isUriResolution.NONE
Cannot benull .- Returns:
- This object.
-
urlEnc
Convenience method for specifying URL-Encoding as the marshalling transmission media type.UrlEncodingSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class. - This serializer is NOT used when using the
RestRequest.formData(String, Object)(and related) methods for constructing the request body. Instead, the part serializer specified viapartSerializer(Class)is used.
UrlEncodingParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/x-www-form-urlencoded" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"application/x-www-form-urlencoded" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().urlEnc().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
urlEncodingSerializer
Returns the URL-encoding serializer sub-builder.- Returns:
- The URL-encoding serializer sub-builder.
-
userTokenHandler
AssignsUserTokenHandlerinstance.Notes:
- This value can be overridden by the
disableConnectionState()method.
- Parameters:
userTokenHandler- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
useSystemProperties
Use system properties when creating and configuring default implementations.Notes:
- The system properties Apache
HttpClientBuilderreads for its own connection manager apply to both pools of the connection manager the defaultcreateConnectionManager()builds, as Apache applies them: with nosslContextorsslSocketFactory,httpsuses the JVM's default SSL socket factory (thejavax.net.ssl.*trust and key stores);https.protocolsandhttps.cipherSuitesrestrict the TLS versions and cipher suites (unless ansslSocketFactoryis set); and unlesshttp.keepAliveisfalse,http.maxConnections(default 5) limits the connections per route, and twice that in total, which makes the connection manager a pooling one.maxConnTotal(int)andmaxConnPerRoute(int)win over that limit. - The proxy system properties apply too (see
proxy(HttpHost)).
- Returns:
- This object.
- See Also:
- The system properties Apache
-
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. RestClientclient = RestClient .create () .json() .useWhitespace() .build();// A bean with a single property public class MyBean {public Stringfoo ="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
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. RestClientclient = RestClient .create () .json() .ws() .build();// A bean with a single property public class MyBean {public Stringfoo ="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
Convenience method for specifying XML as the marshalling transmission media type.XmlSerializerwill be used to serialize POJOs to request bodies unless overridden per request viaRestRequest.serializer(Serializer).- The serializer can be configured using any of the serializer property setters (e.g.
sortCollections()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
XmlParserwill be used to parse POJOs from response bodies unless overridden per request viaRestRequest.parser(Parser).- The parser can be configured using any of the parser property setters (e.g.
MarshallingContextable.Builder.ignoreUnknownBeanProperties()) or bean context property setters (e.g.MarshallingContextable.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/xml" unless overridden viaheaders(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/xml" unless overridden viaheaders(), or per-request viaRestRequest.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 andContent-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. RestClientclient = RestClient.create ().xml().build();- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
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 theHttpClientConnectionManagerreturned bycreateConnectionManager().Subclasses can override this method to provide their own connection manager.
The default implementation returns a new
PoolingHttpClientConnectionManagerifpooled(),maxConnTotal(int),maxConnPerRoute(int)or a positiveconnectionTimeToLivewas set, or thehttp.maxConnectionslimit ofuseSystemProperties()applies (unlesshttp.keepAliveisfalse), or a newBasicHttpClientConnectionManagerif not. It applies thesslContext,sslSocketFactory,sslHostnameVerifier,maxConnTotalandmaxConnPerRoutesettings, which ApacheHttpClientBuilderignores once a connection manager is set. It also applies, to both pools, the other settings ApacheHttpClientBuilderapplies only to a connection manager it builds itself, whether made through this builder or directly on theHttpClientBuilder:publicSuffixMatcher(for the default hostname verifier),defaultSocketConfig,defaultConnectionConfig,connectionTimeToLive(which, likemaxConnTotalandmaxConnPerRoute, makes it aPoolingHttpClientConnectionManager) and the TLS andhttp.maxConnectionssystem properties ofuseSystemProperties(). ADNS resolverset on theHttpClientBuilderis used for ordinary requests only: SSRF-guard-active@Remotecalls always resolve through the SSRF pin. Each of these settings made through this builder also surviveshttpClientBuilder(HttpClientBuilder)replacing theHttpClientBuilder, and always wins over the same setting on theHttpClientBuilder, whichever was set last (unlike Apache's own last-write-wins). An SSL socket factory wins over any SSL context, wherever each was set. TheHttpClientBuilder's settings are read from its fields (it has no getters); if they cannot be read, this method throws anIllegalStateExceptionrather than ignore them.Each
build()calls this method again, so a builder reused afterbuild()gives every client its own connection manager (closing one client does not shut down another's). A connection manager supplied throughconnectionManager(HttpClientConnectionManager)is used as is by every client built.SSRF-guard-active
@Remotecalls do not use this connection manager: the defaultcreateHttpClient()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@Remotecall (one without theallowPrivateUrlsopt-in).The dedicated connection manager copies this one's settings before each guarded call, but it is a separate pool: limits such as
maxTotalapply 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 MyBuilderextends Builder {@Override protected HttpClientConnectionManager createConnectionManager() {return new PoolingHttpClientConnectionManager(); } }// Instantiate. RestClientclient =new MyBuilder().build();- Returns:
- The connection manager to use.
-
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 anHttpClientto 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
HttpClientusing the client builder returned bycreateHttpClientBuilder().Notes:
- SSRF-guard-active
@Remotecalls (ones without theallowPrivateUrlsopt-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 aftersuper.createHttpClient()sets anHttpProcessoron theHttpClientBuilder, adds a request interceptor withaddInterceptorLast(...), or replaces its redirect strategy or request executor (make such changes before callingsuper), or if the builder is a subclass that overridesHttpClientBuilder.build()or one of its exec-chain methods (createMainExec,decorateMainExec,decorateProtocolExec), even an override that returns or decorates nothing but whatsuperbuilt. Ordinary requests are unaffected.
Example:
// A Builder that provides it's own customized HttpClient. public class MyBuilderextends Builder {@Override protected HttpClientBuilder createHttpClient() {return HttpClientBuilder.create ().build(); } }// Instantiate. RestClientclient =new MyBuilder().build();- Returns:
- The HTTP client to use.
- SSRF-guard-active
-
createHttpClientBuilder
Creates an instance of anHttpClientBuilderto be used to create theHttpClient.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 MyBuilderextends Builder {@Override protected HttpClientBuilder createHttpClientBuilder() {return HttpClientBuilder.create (); } }// Instantiate. RestClientclient =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
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.
-