Class MockRestClient.Builder
- Enclosing class:
- MockRestClient
-
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.annotations(Annotation... values) Defines annotations to apply to specific classes and methods.apply(AnnotationWorkList work) Applies a set of applied to this builder.applyAnnotations(Class<?>... from) Same asContext.Builder.applyAnnotations(Object...)but explicitly specifies a class varargs to avoid compilation warnings.applyAnnotations(Object... from) Applies any of the various@XConfig annotations on the specified classes or methods to this context.backoffManager(BackoffManager backoffManager) AssignsBackoffManagerinstance.Set up this client to use BASIC auth.beanClassVisibility(Visibility value) Minimum bean class visibility.Minimum bean constructor visibility.beanContext(BeanContext value) Specifies an already-instantiated bean context to use.beanContext(BeanContext.Builder value) Overrides the bean context builder.beanDictionary(Class<?>... values) Bean dictionary.beanFieldVisibility(Visibility value) Minimum bean field visibility.beanInterceptor(Class<?> on, Class<? extends BeanInterceptor<?>> value) Bean interceptor.BeanMap.put() returns old property value.beanMethodVisibility(Visibility value) Minimum bean method visibility.beanProperties(Class<?> beanClass, String properties) Bean property includes.beanProperties(String beanClassName, String properties) Bean property includes.beanProperties(Map<String, Object> values) Bean property includes.beanPropertiesExcludes(Class<?> beanClass, String properties) Bean property excludes.beanPropertiesExcludes(String beanClassName, String properties) Bean property excludes.beanPropertiesExcludes(Map<String, Object> values) Bean property excludes.beanPropertiesReadOnly(Class<?> beanClass, String properties) Read-only bean properties.beanPropertiesReadOnly(String beanClassName, String properties) Read-only bean properties.beanPropertiesReadOnly(Map<String, Object> values) Read-only bean properties.beanPropertiesWriteOnly(Class<?> beanClass, String properties) Write-only bean properties.beanPropertiesWriteOnly(String beanClassName, String properties) Write-only bean properties.beanPropertiesWriteOnly(Map<String, Object> values) Write-only bean properties.Beans require no-arg constructors.Beans require Serializable interface.Beans require setters for getters.build()Build the object.Specifies a cache to use for hashkey-based caching.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.contextPath(String value) Identifies the context path for the REST resource.copy()Copy creator.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.dictionaryOn(Class<?> on, Class<?>... values) Bean dictionary.Disables authentication scheme caching.Disables automatic request recovery and re-execution.Beans don't require at least one property.Disables connection state tracking.Disables automatic content decompression.Disables state (cookie) management.Don't silently ignore missing setters.Don't ignore transient fields.Don't ignore unknown properties with null values.Don't use interface proxies.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.POJO example.POJO example.executorService(ExecutorService executorService, boolean shutdownOnClose) RestClient configuration property: Executor service.Find fluent setters.findFluentSetters(Class<?> on) Find fluent setters.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.Appends a header to all requests.Appends a header to all requests using a dynamic value.Appends multiple headers to all requests.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.httpProcessor(HttpProcessor httpprocessor) AssignsHttpProcessorinstance.Ignore errors.Ignore invocation errors on getters.Ignore invocation errors on setters.BeanTraverse configuration property: Ignore recursion errors.Ignore unknown properties.Ignore unknown enum values.Specifies a pre-instantiated bean for theContext.Builder.build()method to return.Implementation classes.implClasses(Map<Class<?>, Class<?>> values) Implementation classes.initialDepth(int value) BeanTraverse configuration property: Initial depth.interceptors(Class<?>... values) RestClient configuration property: Call interceptors.interceptors(Object... value) Call interceptors.interfaceClass(Class<?> on, Class<?> value) Identifies a class to be used as the interface class for the specified class and all subclasses.interfaces(Class<?>... value) Identifies a set of interfaces.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.Context configuration property: Locale.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.notBeanClasses(Class<?>... values) Bean class exclusions.notBeanPackages(String... values) Bean package exclusions.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.Parsers.Parsers.partParser(Class<? extends HttpPartParser> value) Part parser.partParser(HttpPartParser value) Part parser.partSerializer(Class<? extends HttpPartSerializer> value) Part serializer.partSerializer(HttpPartSerializer value) Part serializer.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.Add resolved path variables to this client.Add resolved path variables to this client.Convenience method for specifying Plain Text as the marshalling transmission media type.pooled()When called, theRestClient.Builder.createConnectionManager()method will return aPoolingHttpClientConnectionManagerinstead of aBasicHttpClientConnectionManager.propertyNamer(Class<?> on, Class<? extends PropertyNamer> value) Bean property namerpropertyNamer(Class<? extends PropertyNamer> value) Bean property namerAssigns default proxy value.proxyAuthenticationStrategy(AuthenticationStrategy proxyAuthStrategy) AssignsAuthenticationStrategyinstance for proxy authentication.publicSuffixMatcher(PublicSuffixMatcher publicSuffixMatcher) Assigns file containing public suffix matcher.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.quoteChar(char value) WriterSerializer configuration property: Quote character.redirectStrategy(RedirectStrategy redirectStrategy) AssignsRedirectStrategyinstance.requestExecutor(HttpRequestExecutor requestExec) AssignsHttpRequestExecutorinstance.Specifies theRest-annotated bean class or instance to test against.restContext(RestContext value) Specifies theRestContextcreated for the REST bean.retryHandler(HttpRequestRetryHandler retryHandler) AssignsHttpRequestRetryHandlerinstance.RestClient configuration property: Root URI.routePlanner(HttpRoutePlanner routePlanner) AssignsHttpRoutePlannerinstance.schemePortResolver(SchemePortResolver schemePortResolver) AssignsSchemePortResolverinstance.serializer(Class<? extends Serializer> value) Serializer.serializer(Serializer value) Serializer.serializers(Class<? extends Serializer>... value) Serializers.serializers(Serializer... value) Serializers.serviceUnavailableRetryStrategy(ServiceUnavailableRetryStrategy serviceUnavailStrategy) AssignsServiceUnavailableRetryStrategyinstance.servletPath(String value) Identifies the servlet path for the REST resource.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.Sort bean properties.sortProperties(Class<?>... on) Sort bean properties.sq()WriterSerializer configuration property: Quote character.sslContext(SSLContext sslContext) AssignsSSLContextinstance.sslHostnameVerifier(HostnameVerifier hostnameVerifier) AssignsHostnameVerifierinstance.sslSocketFactory(LayeredConnectionSocketFactory sslSocketFactory) AssignsLayeredConnectionSocketFactoryinstance.Identifies a stop class for the annotated class.strict()Parser configuration property: Strict mode.Suppress logging on this client.<T,S> MockRestClient.Builder swap(Class<T> normalClass, Class<S> swappedClass, ThrowingFunction<T, S> swapFunction) A shortcut for defining aFunctionalSwap.<T,S> MockRestClient.Builder swap(Class<T> normalClass, Class<S> swappedClass, ThrowingFunction<T, S> swapFunction, ThrowingFunction<S, T> unswapFunction) A shortcut for defining aFunctionalSwap.Same asBeanContextable.Builder.swaps(Object...)except explicitly specifies class varargs to avoid compilation warnings.Java object swaps.targetAuthenticationStrategy(AuthenticationStrategy targetAuthStrategy) AssignsAuthenticationStrategyinstance for target host authentication.Context configuration property: TimeZone.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.Associates a context class with this builder.An identifying name for this class.typePropertyName(Class<?> on, String value) Bean type property name.typePropertyName(String value) Bean type property name.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.Use enum names.Use Java Introspector.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.rest.client.RestClient.Builder
callHandler, createCallHandler, createConnectionManager, createFormData, createHeaderData, createHttpClient, createHttpClientBuilder, createParsers, createPartParser, createPartSerializer, createPathData, createQueryData, createSerializers, createUrlEncodingSerializer, formData, formDataDefault, getRootUri, headers, headersDefault, httpClientBuilder, parsers, partParser, partSerializer, pathData, pathDataDefault, queryData, queryDataDefault, serializers, universal, urlEncodingSerializerMethods inherited from class org.apache.juneau.BeanContextable.Builder
beanContext, beanContext, hashKeyMethods inherited from class org.apache.juneau.Context.Builder
annotations, asSubtype, build, canApply, debug, getApplied, getType, isDebug, registerBuilders
-
Constructor Details
-
Builder
protected Builder()No-arg constructor.Provided so that this class can be easily subclassed.
-
-
Method Details
-
accept
Description copied from class:RestClient.BuilderAppends anAccept header on this request.This is a shortcut for calling
headerData().append(Accept. .of (value ))- Overrides:
acceptin classRestClient.Builder- Parameters:
value- The new header value.
Can benull (no Accept header will be added).- Returns:
- This object.
- See Also:
-
acceptCharset
Description copied from class:RestClient.BuilderSets the value for theAccept-Charset request header on all requests.This is a shortcut for calling
headerData().append(AcceptCharset. .of (value ))- Overrides:
acceptCharsetin classRestClient.Builder- Parameters:
value- The new header value.
Can benull (no Accept-Charset header will be added).- Returns:
- This object.
- See Also:
-
addBeanTypes
Description copied from class:RestClient.BuilderSerializer 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:
RestClient.Builder.addRootType()- Affects whether'_type' is added to root node.RestClient.Builder.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. @Bean (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:
- Overrides:
addBeanTypesin classRestClient.Builder- Returns:
- This object.
-
addInterceptorFirst
Description copied from class:RestClient.BuilderAdds this protocol interceptor to the head of the protocol processing list.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
addInterceptorFirstin classRestClient.Builder- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorFirst
Description copied from class:RestClient.BuilderAdds this protocol interceptor to the head of the protocol processing list.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
addInterceptorFirstin classRestClient.Builder- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorLast
Description copied from class:RestClient.BuilderAdds this protocol interceptor to the tail of the protocol processing list.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
addInterceptorLastin classRestClient.Builder- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addInterceptorLast
Description copied from class:RestClient.BuilderAdds this protocol interceptor to the tail of the protocol processing list.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
addInterceptorLastin classRestClient.Builder- Parameters:
itcp- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
addRootType
Description copied from class:RestClient.BuilderSerializer 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
@Bean(typeName)value, a'_type' attribute will only be added when this setting is enabled.Note the differences between the following settings:
RestClient.Builder.addRootType()- Affects whether'_type' is added to root node.RestClient.Builder.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. @Bean (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:
- Overrides:
addRootTypein classRestClient.Builder- Returns:
- This object.
-
annotations
Description copied from class:Context.BuilderDefines annotations to apply to specific classes and methods.Allows you to dynamically apply Juneau annotations typically applied directly to classes and methods. Useful in cases where you want to use the functionality of the annotation on beans and bean properties but do not have access to the code to do so.
As a rule, any Juneau annotation with an
on() method can be used with this setting.The following example shows the equivalent methods for applying the
@Beanannotation:// Class with explicit annotation. @Bean (properties="street,city,state" )public class A {...}// Class with annotation applied via @BeanConfig public class B {...}// Java REST method with @BeanConfig annotation. @RestGet (...)@Bean (on="B" , properties="street,city,state" )public void doFoo() {...}In general, the underlying framework uses this method when it finds dynamically applied annotations on config annotations. However, concrete implementations of annotations are also provided that can be passed directly into builder classes like so:
// Create a concrete @Bean annotation. Bean annotation = BeanAnnotation.create (B.class ).properties("street,city,state" ).build();// Apply it to a serializer. WriterSerializerserializer = JsonSerializer.create ().annotations(annotation ).build();// Serialize a bean with the dynamically applied annotation. Stringjson =serializer .serialize(new B());The following is the list of annotations builders provided that can be constructed and passed into the builder class:
BeanAnnotationBeancAnnotationBeanIgnoreAnnotationBeanpAnnotationExampleAnnotationNamePropertyAnnotationParentPropertyAnnotationSwapAnnotationUriAnnotationCsvAnnotationHtmlAnnotationJsonAnnotationSchemaAnnotationMsgPackAnnotationOpenApiAnnotationPlainTextAnnotationSoapXmlAnnotationUonAnnotationUrlEncodingAnnotationXmlAnnotation
The syntax for the
on() pattern match parameter depends on whether it applies to a class, method, field, or constructor. The valid pattern matches are:- Classes:
- Fully qualified:
"com.foo.MyClass"
- Fully qualified inner class:
"com.foo.MyClass$Inner1$Inner2"
- Simple:
"MyClass"
- Simple inner:
"MyClass$Inner1$Inner2" "Inner1$Inner2" "Inner2"
- Fully qualified:
- Methods:
- Fully qualified with args:
"com.foo.MyClass.myMethod(String,int)" "com.foo.MyClass.myMethod(java.lang.String,int)" "com.foo.MyClass.myMethod()"
- Fully qualified:
"com.foo.MyClass.myMethod"
- Simple with args:
"MyClass.myMethod(String,int)" "MyClass.myMethod(java.lang.String,int)" "MyClass.myMethod()"
- Simple:
"MyClass.myMethod"
- Simple inner class:
"MyClass$Inner1$Inner2.myMethod" "Inner1$Inner2.myMethod" "Inner2.myMethod"
- Fully qualified with args:
- Fields:
- Fully qualified:
"com.foo.MyClass.myField"
- Simple:
"MyClass.myField"
- Simple inner class:
"MyClass$Inner1$Inner2.myField" "Inner1$Inner2.myField" "Inner2.myField"
- Fully qualified:
- Constructors:
- Fully qualified with args:
"com.foo.MyClass(String,int)" "com.foo.MyClass(java.lang.String,int)" "com.foo.MyClass()"
- Simple with args:
"MyClass(String,int)" "MyClass(java.lang.String,int)" "MyClass()"
- Simple inner class:
"MyClass$Inner1$Inner2()" "Inner1$Inner2()" "Inner2()"
- Fully qualified with args:
- A comma-delimited list of anything on this list.
See Also:
- Overrides:
annotationsin classRestClient.Builder- Parameters:
values- The annotations to register with the context.
Cannot containnull values.- Returns:
- This object.
-
apply
Description copied from class:Context.BuilderApplies a set of applied to this builder.An
AnnotationWorkconsists of a single pair ofAnnotationInfothat represents an annotation instance, andAnnotationApplierwhich represents the code used to apply the values in that annotation to a specific builder.Example:
// A class annotated with a config annotation. @BeanConfig (sortProperties="$S{sortProperties,false}" )public class MyClass {...}// Find all annotations that themselves are annotated with @ContextPropertiesApply. Stream<AnnotationInfo<?>>annotations = ClassInfo.of (MyClass.class ).getAnnotations().stream().filter(CONTEXT_APPLY_FILTER ); VarResolverSessionvrs = VarResolver.DEFAULT .createSession(); AnnotationWorkListwork = AnnotationWorkList.of(vrs ,annotations );// Apply any settings found on the annotations. WriterSerializerserializer = JsonSerializer .create () .apply(work ) .build();- Overrides:
applyin classRestClient.Builder- Parameters:
work- The list of annotations and appliers to apply to this builder.
Cannot benull .- Returns:
- This object.
-
applyAnnotations
Description copied from class:Context.BuilderSame asContext.Builder.applyAnnotations(Object...)but explicitly specifies a class varargs to avoid compilation warnings.- Overrides:
applyAnnotationsin classRestClient.Builder- Parameters:
from- The classes or methods on which the annotations are defined.
Cannot containnull values.- Returns:
- This object.
-
applyAnnotations
Description copied from class:Context.BuilderApplies any of the various@XConfig annotations on the specified classes or methods to this context.Any annotations found that themselves are annotated with
ContextApplywill be resolved and applied as properties to this builder. These annotations include:BeanConfigCsvConfigHtmlConfigHtmlDocConfigJsonConfigJsonSchemaConfigMsgPackConfigOpenApiConfigParserConfigPlainTextConfigSerializerConfigSoapXmlConfigUonConfigUrlEncodingConfigXmlConfigRdfConfig
Annotations on classes are appended in the following order:
- On the package of this class.
- On interfaces ordered parent-to-child.
- On parent classes ordered parent-to-child.
- On this class.
Annotations on methods are appended in the following order:
- On the package of the method class.
- On interfaces ordered parent-to-child.
- On parent classes ordered parent-to-child.
- On the method class.
- On this method and matching methods ordered parent-to-child.
The default var resolver
VarResolver.DEFAULTis used to resolve any variables in annotation field values.Example:
// A class annotated with a config annotation. @BeanConfig (sortProperties="$S{sortProperties,false}" )public class MyClass {...}// Apply any settings found on the annotations. WriterSerializerserializer = JsonSerializer .create () .applyAnnotations(MyClass.class ) .build();// A method annotated with a config annotation. public class MyClass {@BeanConfig (sortProperties="$S{sortProperties,false}" )public void myMethod() {...} }// Apply any settings found on the annotations. WriterSerializerserializer = JsonSerializer .create () .applyAnnotations(MyClass.class .getMethod("myMethod" )) .build();- Overrides:
applyAnnotationsin classRestClient.Builder- Parameters:
from- The classes or methods on which the annotations are defined. Can be any of the following types:ClassClassInfoMethodMethodInfo- A collection/stream/array of anything on this list.
Cannot containnull values.
- Returns:
- This object.
-
backoffManager
Description copied from class:RestClient.BuilderAssignsBackoffManagerinstance.- Overrides:
backoffManagerin classRestClient.Builder- Parameters:
backoffManager- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
basicAuth
Description copied from class:RestClient.BuilderSet 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();- Overrides:
basicAuthin classRestClient.Builder- 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.
-
beanClassVisibility
Description copied from class:BeanContextable.BuilderMinimum bean class visibility.Classes are not considered beans unless they meet the minimum visibility requirements. For example, if the visibility is
PUBLIC and the bean class isprotected , then the class will not be interpreted as a bean class and be serialized as a string. Use this setting to reduce the visibility requirement.Example:
// A bean with a protected class and one field. protected class MyBean {public Stringfoo ="bar" ; }// Create a serializer that's capable of serializing the class. WriterSerializerserializer = JsonSerializer .create () .beanClassVisibility(PROTECTED ) .build();// Produces: {"foo","bar"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanannotation can be used on a non-public bean class to override this setting. - The
@BeanIgnoreannotation can also be used on a public bean class to ignore it as a bean.
See Also:
- Overrides:
beanClassVisibilityin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isVisibility.PUBLIC.
Cannot benull .- Returns:
- This object.
- The
-
beanConstructorVisibility
Description copied from class:BeanContextable.BuilderMinimum bean constructor visibility.Only look for constructors with the specified minimum visibility.
This setting affects the logic for finding no-arg constructors for bean. Normally, only
public no-arg constructors are used. Use this setting if you want to reduce the visibility requirement.Example:
// A bean with a protected constructor and one field. public class MyBean {public Stringfoo ;protected MyBean() {} }// Create a parser capable of calling the protected constructor. ReaderParserparser = ReaderParser .create () .beanConstructorVisibility(PROTECTED ) .build();// Use it. MyBeanbean =parser .parse("{foo:'bar'}" , MyBean.class );Notes:
- The
@Beancannotation can also be used to expose a non-public constructor. - The
@BeanIgnoreannotation can also be used on a public bean constructor to ignore it.
See Also:
- Overrides:
beanConstructorVisibilityin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isVisibility.PUBLIC.
Cannot benull .- Returns:
- This object.
- The
-
beanContext
Description copied from class:BeanContextable.BuilderSpecifies an already-instantiated bean context to use.Provides an optimization for cases where serializers and parsers can use an existing bean context without having to go through
. An example isbeanContext .copy().build()BeanContext.getBeanToStringSerializer().- Overrides:
beanContextin classRestClient.Builder- Parameters:
value- The bean context to use.
Cannot benull .- Returns:
- This object.
-
beanContext
Description copied from class:BeanContextable.BuilderOverrides the bean context builder.Used when sharing bean context builders across multiple context objects. For example,
JsonSchemaGenerator.Builderuses this to apply common bean settings with the JSON serializer and parser.- Overrides:
beanContextin classRestClient.Builder- Parameters:
value- The new value for this setting.
Cannot benull .- Returns:
- This object.
-
beanDictionary
Description copied from class:BeanContextable.BuilderBean dictionary.The list of classes that make up the bean dictionary in this bean context.
Values are prepended to the list so that later calls can override classes of earlier calls.
A dictionary is a name/class mapping used to find class types during parsing when they cannot be inferred through reflection. The names are defined through the
@Bean(typeName)annotation defined on the bean class. For example, if a classFoo has a type-name of"myfoo" , then it would end up serialized as"{_type:'myfoo',...}" in JSON or"<myfoo>...</myfoo>" in XML.This setting tells the parsers which classes to look for when resolving
"_type" attributes.Values can consist of any of the following types:
- Any bean class that specifies a value for
@Bean(typeName). - Any subclass of
BeanDictionaryListcontaining a collection of bean classes with type name annotations. - Any subclass of
BeanDictionaryMapcontaining a mapping of type names to classes without type name annotations. - Any array or collection of the objects above.
Example:
// POJOs with @Bean(name) annotations. @Bean (typeName="foo" )public class Foo {...}@Bean (typeName="bar" )public class Bar {...}// Create a parser and tell it which classes to try to resolve. ReaderParserparser = JsonParser .create () .dictionary(Foo.class , Bar.class ) .addBeanTypes() .build();// A bean with a field with an indeterminate type. public class MyBean {public ObjectmySimpleField ; }// Parse bean. MyBeanbean =parser .parse("{mySimpleField:{_type:'foo',...}}" , MyBean.class );Another option is to use the
Bean.dictionary()annotation on the POJO class itself:// Instead of by parser, define a bean dictionary on a class through an annotation. // This applies to all properties on this class and all subclasses. @Bean (dictionary={Foo.class ,Bar.class })public class MyBean {public ObjectmySimpleField ;// May contain Foo or Bar object. public Map<String,Object>myMapField ;// May contain Foo or Bar objects. }A typical usage is to allow for HTML documents to be parsed back into HTML beans:
// Use the predefined HTML5 bean dictionary which is a BeanDictionaryList. ReaderParserparser = HtmlParser .create () .dictionary(HtmlBeanDictionary.class ) .build();// Parse an HTML body into HTML beans. Bodybody =parser .parse("<body><ul><li>foo</li><li>bar</li></ul>" , Body.class );See Also:
- Overrides:
beanDictionaryin classRestClient.Builder- Parameters:
values- The values to add to this setting.
Cannot containnull values.- Returns:
- This object.
- Any bean class that specifies a value for
-
beanFieldVisibility
Description copied from class:BeanContextable.BuilderMinimum bean field visibility.Only look for bean fields with the specified minimum visibility.
This affects which fields on a bean class are considered bean properties. Normally only
public fields are considered. Use this setting if you want to reduce the visibility requirement.Example:
// A bean with a protected field. public class MyBean {protected Stringfoo ="bar" ; }// Create a serializer that recognizes the protected field. WriterSerializerserializer = JsonSerializer .create () .beanFieldVisibility(PROTECTED ) .build();// Produces: {"foo":"bar"} Stringjson =serializer .serialize(new MyBean());Bean fields can be ignored as properties entirely by setting the value to
Visibility.NONE// Disable using fields as properties entirely. WriterSerializerserializer = JsonSerializer .create () .beanFieldVisibility(NONE ) .build();Notes:
- The
@Beanpannotation can also be used to expose a non-public field. - The
@BeanIgnoreannotation can also be used on a public bean field to ignore it as a bean property.
See Also:
- Overrides:
beanFieldVisibilityin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isVisibility.PUBLIC.
Cannot benull .- Returns:
- This object.
- The
-
beanInterceptor
public MockRestClient.Builder beanInterceptor(Class<?> on, Class<? extends BeanInterceptor<?>> value) Description copied from class:BeanContextable.BuilderBean interceptor.Bean interceptors can be used to intercept calls to getters and setters and alter their values in transit.
Example:
// Interceptor that strips out sensitive information. public class AddressInterceptorextends BeanInterceptor<Address> {public Object readProperty(Addressbean , Stringname , Objectvalue ) {if ("taxInfo" .equals(name ))return "redacted" ;return value ; }public Object writeProperty(Addressbean , Stringname , Objectvalue ) {if ("taxInfo" .equals(name ) &&"redacted" .equals(value ))return TaxInfoUtils.lookup (bean .getStreet(),bean .getCity(),bean .getState());return value ; } }// Our bean class. public class Address {public String getTaxInfo() {...}public void setTaxInfo(Stringvalue ) {...} }// Register filter on serializer or parser. WriterSerializerserializer = JsonSerializer .create () .beanInterceptor(Address.class , AddressInterceptor.class ) .build();// Produces: {"taxInfo":"redacted"} Stringjson =serializer .serialize(new Address());See Also:
- Overrides:
beanInterceptorin classRestClient.Builder- Parameters:
on- The bean that the filter applies to.
Cannot benull .value- The new value for this setting.
Cannot benull .- Returns:
- This object.
-
beanMapPutReturnsOldValue
Description copied from class:BeanContextable.BuilderBeanMap.put() returns old property value.When enabled, then the
BeanMap.put()method will return old property values. Otherwise, it returnsnull .Disabled by default because it introduces a slight performance penalty during serialization.
Example:
// Create a context that creates BeanMaps with normal put() behavior. BeanContextcontext = BeanContext .create () .beanMapPutReturnsOldValue() .build(); BeanMap<MyBean>beanMap =context .createSession().toBeanMap(new MyBean());beanMap .put("foo" ,"bar" ); ObjectoldValue =beanMap .put("foo" ,"baz" );// oldValue == "bar" See Also:
- Overrides:
beanMapPutReturnsOldValuein classBeanContextable.Builder- Returns:
- This object.
-
beanMethodVisibility
Description copied from class:BeanContextable.BuilderMinimum bean method visibility.Only look for bean methods with the specified minimum visibility.
This affects which methods are detected as getters and setters on a bean class. Normally only
public getters and setters are considered. Use this setting if you want to reduce the visibility requirement.Example:
// A bean with a protected getter. public class MyBean {public String getFoo() {return "foo" ; }protected String getBar() {return "bar" ; } }// Create a serializer that looks for protected getters and setters. WriterSerializerserializer = JsonSerializer .create () .beanMethodVisibility(PROTECTED ) .build();// Produces: {"foo":"foo","bar":"bar"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanpannotation can also be used to expose a non-public method. - The
@BeanIgnoreannotation can also be used on a public bean getter/setter to ignore it as a bean property.
See Also:
- Overrides:
beanMethodVisibilityin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isVisibility.PUBLIC
Cannot benull .- Returns:
- This object.
- The
-
beanProperties
Description copied from class:BeanContextable.BuilderBean property includes.Specifies the set and order of names of properties associated with the bean class.
For example,
beanProperties(MyBean. means only serialize theclass ,"foo,bar" )foo andbar properties on the specified bean. Likewise, parsing will ignore any bean properties not specified and either throw an exception or silently ignore them depending on whetherBeanContextable.Builder.ignoreUnknownBeanProperties()has been called.This value is entirely optional if you simply want to expose all the getters and public fields on a class as bean properties. However, it's useful if you want certain getters to be ignored or you want the properties to be serialized in a particular order. Note that on IBM JREs, the property order is the same as the order in the source code, whereas on Oracle JREs, the order is entirely random.
Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that includes only the 'foo' and 'bar' properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanProperties(MyBean.class ,"foo,bar" ) .build();// Produces: {"foo":"foo","bar":"bar"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClass ).properties(properties ).build());See Also:
Bean.properties()/Bean.p()- On an annotation on the bean class itself.
- Overrides:
beanPropertiesin classRestClient.Builder- Parameters:
beanClass- The bean class.properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanProperties
Description copied from class:BeanContextable.BuilderBean property includes.Specifies the set and order of names of properties associated with bean classes.
For example,
beanProperties(AMap. means only serialize theof ("MyBean" ,"foo,bar" ))foo andbar properties on the specified bean. Likewise, parsing will ignore any bean properties not specified and either throw an exception or silently ignore them depending on whetherBeanContextable.Builder.ignoreUnknownBeanProperties()has been called.This value is entirely optional if you simply want to expose all the getters and public fields on a class as bean properties. However, it's useful if you want certain getters to be ignored or you want the properties to be serialized in a particular order. Note that on IBM JREs, the property order is the same as the order in the source code, whereas on Oracle JREs, the order is entirely random.
Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that includes only the 'foo' and 'bar' properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanProperties(AMap.of ("MyBean" ,"foo,bar" )) .build();// Produces: {"foo":"foo","bar":"bar"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code for each entry:
builder .annotations(BeanAnnotation.create (key ).properties(value .toString()).build());See Also:
Bean.properties()/Bean.p()- On an annotation on the bean class itself.
- Overrides:
beanPropertiesin classRestClient.Builder- Parameters:
values- The values to add to this builder.
Keys are bean class names which can be a simple name, fully-qualified name, or"*" for all beans.
Values are comma-delimited lists of property names. Non-String objects are first converted to Strings.
Cannot benull .- Returns:
- This object.
-
beanProperties
Description copied from class:BeanContextable.BuilderBean property includes.Specifies the set and order of names of properties associated with the bean class.
For example,
beanProperties( means only serialize the"MyBean" ,"foo,bar" )foo andbar properties on the specified bean. Likewise, parsing will ignore any bean properties not specified and either throw an exception or silently ignore them depending on whetherBeanContextable.Builder.ignoreUnknownBeanProperties()has been called.This value is entirely optional if you simply want to expose all the getters and public fields on a class as bean properties. However, it's useful if you want certain getters to be ignored or you want the properties to be serialized in a particular order. Note that on IBM JREs, the property order is the same as the order in the source code, whereas on Oracle JREs, the order is entirely random.
Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that includes only the 'foo' and 'bar' properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanProperties("MyBean" ,"foo,bar" ) .build();// Produces: {"foo":"foo","bar":"bar"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClassName ).properties(properties ).build());See Also:
Bean.properties()/Bean.p()- On an annotation on the bean class itself.
- Overrides:
beanPropertiesin classRestClient.Builder- Parameters:
beanClassName- The bean class name.
Can be a simple name, fully-qualified name, or"*" for all beans.
Cannot benull .properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesExcludes
Description copied from class:BeanContextable.BuilderBean property excludes.Specifies to exclude the specified list of properties for the specified bean class.
Same as
BeanContextable.Builder.beanProperties(Class, String)except you specify a list of bean property names that you want to exclude from serialization.Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that excludes the "bar" and "baz" properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesExcludes(MyBean.class ,"bar,baz" ) .build();// Produces: {"foo":"foo"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClass ).excludeProperties(properties ).build());See Also:
- Overrides:
beanPropertiesExcludesin classRestClient.Builder- Parameters:
beanClass- The bean class.properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesExcludes
Description copied from class:BeanContextable.BuilderBean property excludes.Specifies to exclude the specified list of properties for the specified bean classes.
Same as
BeanContextable.Builder.beanProperties(Map)except you specify a list of bean property names that you want to exclude from serialization.Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that excludes the "bar" and "baz" properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesExcludes(AMap.of("MyBean" ,"bar,baz" )) .build();// Produces: {"foo":"foo"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code for each entry:
builder .annotations(BeanAnnotation.create (key ).excludeProperties(value .toString()).build());See Also:
- Overrides:
beanPropertiesExcludesin classRestClient.Builder- Parameters:
values- The values to add to this builder.
Keys are bean class names which can be a simple name, fully-qualified name, or"*" for all beans.
Values are comma-delimited lists of property names. Non-String objects are first converted to Strings.
Cannot benull .- Returns:
- This object.
-
beanPropertiesExcludes
Description copied from class:BeanContextable.BuilderBean property excludes.Specifies to exclude the specified list of properties for the specified bean class.
Same as
BeanContextable.Builder.beanPropertiesExcludes(String, String)except you specify a list of bean property names that you want to exclude from serialization.Setting applies to specified class and all subclasses.
Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ="foo" ,bar ="bar" ,baz ="baz" ; }// Create a serializer that excludes the "bar" and "baz" properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesExcludes("MyBean" ,"bar,baz" ) .build();// Produces: {"foo":"foo"} Stringjson =serializer .serialize(new MyBean());This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClassName ).excludeProperties(properties ).build());See Also:
- Overrides:
beanPropertiesExcludesin classRestClient.Builder- Parameters:
beanClassName- The bean class name.
Can be a simple name, fully-qualified name, or"*" for all bean classes.
Cannot benull .properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesReadOnly
Description copied from class:BeanContextable.BuilderRead-only bean properties.Specifies one or more properties on a bean that are read-only despite having valid getters. Serializers will serialize such properties as usual, but parsers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with read-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesReadOnly(MyBean.class ,"bar,baz" ) .build();// All 3 properties will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with read-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesReadOnly(MyBean.class ,"bar,baz" ) .ignoreUnknownBeanProperties() .build();// Parser ignores bar and baz properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClass ).readOnlyProperties(properties ).build());See Also:
- Overrides:
beanPropertiesReadOnlyin classRestClient.Builder- Parameters:
beanClass- The bean class.properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesReadOnly
Description copied from class:BeanContextable.BuilderRead-only bean properties.Specifies one or more properties on beans that are read-only despite having valid getters. Serializers will serialize such properties as usual, but parsers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with read-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesReadOnly(AMap.of ("MyBean" ,"bar,baz" )) .build();// All 3 properties will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with read-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesReadOnly(AMap.of ("MyBean" ,"bar,baz" )) .ignoreUnknownBeanProperties() .build();// Parser ignores bar and baz properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code for each entry:
builder .annotations(BeanAnnotation.create (key ).readOnlyProperties(value .toString()).build());See Also:
- Overrides:
beanPropertiesReadOnlyin classRestClient.Builder- Parameters:
values- The values to add to this builder.
Keys are bean class names which can be a simple name, fully-qualified name, or"*" for all beans.
Values are comma-delimited lists of property names. Non-String objects are first converted to Strings.
Cannot benull .- Returns:
- This object.
-
beanPropertiesReadOnly
Description copied from class:BeanContextable.BuilderRead-only bean properties.Specifies one or more properties on a bean that are read-only despite having valid getters. Serializers will serialize such properties as usual, but parsers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with read-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesReadOnly("MyBean" ,"bar,baz" ) .build();// All 3 properties will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with read-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesReadOnly("MyBean" ,"bar,baz" ) .ignoreUnknownBeanProperties() .build();// Parser ignores bar and baz properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClassName ).readOnlyProperties(properties ).build());See Also:
- Overrides:
beanPropertiesReadOnlyin classRestClient.Builder- Parameters:
beanClassName- The bean class name.
Can be a simple name, fully-qualified name, or"*" for all bean classes.
Cannot benull .properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesWriteOnly
Description copied from class:BeanContextable.BuilderWrite-only bean properties.Specifies one or more properties on a bean that are write-only despite having valid setters. Parsers will parse such properties as usual, but serializers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with write-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesWriteOnly(MyBean.class ,"bar,baz" ) .build();// Only foo will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with write-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesWriteOnly(MyBean.class ,"bar,baz" ) .build();// Parser parses all 3 properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClass ).writeOnlyProperties(properties ).build());See Also:
- Overrides:
beanPropertiesWriteOnlyin classRestClient.Builder- Parameters:
beanClass- The bean class.properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beanPropertiesWriteOnly
Description copied from class:BeanContextable.BuilderWrite-only bean properties.Specifies one or more properties on a bean that are write-only despite having valid setters. Parsers will parse such properties as usual, but serializers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with write-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesWriteOnly(AMap.of ("MyBean" ,"bar,baz" )) .build();// Only foo will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with write-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesWriteOnly(AMap.of ("MyBean" ,"bar,baz" )) .build();// Parser parses all 3 properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code for each entry:
builder .annotations(BeanAnnotation.create (key ).writeOnlyProperties(value .toString()).build());See Also:
- Overrides:
beanPropertiesWriteOnlyin classRestClient.Builder- Parameters:
values- The values to add to this builder.
Keys are bean class names which can be a simple name, fully-qualified name, or"*" for all beans.
Values are comma-delimited lists of property names. Non-String objects are first converted to Strings.
Cannot benull .- Returns:
- This object.
-
beanPropertiesWriteOnly
Description copied from class:BeanContextable.BuilderWrite-only bean properties.Specifies one or more properties on a bean that are write-only despite having valid setters. Parsers will parse such properties as usual, but serializers will silently ignore them. Note that this is different from the
beanProperties/beanPropertiesExcludessettings which include or exclude properties for both serializers and parsers.Example:
// A bean with 3 properties. public class MyBean {public Stringfoo ,bar ,baz ; }// Create a serializer with write-only property settings. WriterSerializerserializer = JsonSerializer .create () .beanPropertiesWriteOnly("MyBean" ,"bar,baz" ) .build();// Only foo will be serialized. Stringjson =serializer .serialize(new MyBean());// Create a parser with write-only property settings. ReaderParserparser = JsonParser .create () .beanPropertiesWriteOnly("MyBean" ,"bar,baz" ) .build();// Parser parses all 3 properties. MyBeanbean =parser .parse("{foo:'foo',bar:'bar',baz:'baz'}" , MyBean.class );This method is functionally equivalent to the following code:
builder .annotations(BeanAnnotation.create (beanClassName ).writeOnlyProperties(properties ).build());See Also:
- Overrides:
beanPropertiesWriteOnlyin classRestClient.Builder- Parameters:
beanClassName- The bean class name.
Can be a simple name, fully-qualified name, or"*" for all bean classes.
Cannot benull .properties- Comma-delimited list of property names.
Cannot benull .- Returns:
- This object.
-
beansRequireDefaultConstructor
Description copied from class:BeanContextable.BuilderBeans require no-arg constructors.When enabled, a Java class must implement a default no-arg constructor to be considered a bean. Otherwise, the bean will be serialized as a string using the
Object.toString()method.Example:
// A bean without a no-arg constructor. public class MyBean {// A property method. public Stringfoo ="bar" ;// A no-arg constructor public MyBean(Stringfoo ) {this .foo =foo ; }@Override public String toString() {return "bar" ; } }// Create a serializer that ignores beans without default constructors. WriterSerializerserializer = JsonSerializer .create () .beansRequireDefaultConstructor() .build();// Produces: "bar" Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanannotation can be used on a bean class to override this setting. - The
@BeanIgnoreannotation can also be used on a class to ignore it as a bean.
See Also:
- Overrides:
beansRequireDefaultConstructorin classRestClient.Builder- Returns:
- This object.
- The
-
beansRequireSerializable
Description copied from class:BeanContextable.BuilderBeans require Serializable interface.When enabled, a Java class must implement the
Serializableinterface to be considered a bean. Otherwise, the bean will be serialized as a string using theObject.toString()method.Example:
// A bean without a Serializable interface. public class MyBean {// A property method. public Stringfoo ="bar" ;@Override public String toString() {return "bar" ; } }// Create a serializer that ignores beans not implementing Serializable. WriterSerializerserializer = JsonSerializer .create () .beansRequireSerializable() .build();// Produces: "bar" Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanannotation can be used on a bean class to override this setting. - The
@BeanIgnoreannotation can also be used on a class to ignore it as a bean.
See Also:
- Overrides:
beansRequireSerializablein classRestClient.Builder- Returns:
- This object.
- The
-
beansRequireSettersForGetters
Description copied from class:BeanContextable.BuilderBeans require setters for getters.When enabled, ignore read-only properties (properties with getters but not setters).
Example:
// A bean without a Serializable interface. public class MyBean {// A read/write property. public String getFoo() {return "foo" ; }public void setFoo(Stringfoo ) { ... }// A read-only property. public String getBar() {return "bar" ; } }// Create a serializer that ignores bean properties without setters. WriterSerializerserializer = JsonSerializer .create () .beansRequireSettersForGetters() .build();// Produces: {"foo":"foo"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanpannotation can be used on the getter to override this setting. - The
@BeanIgnoreannotation can also be used on getters to ignore them as bean properties.
See Also:
- Overrides:
beansRequireSettersForGettersin classRestClient.Builder- Returns:
- This object.
- The
-
build
Description copied from class:Context.BuilderBuild the object.- Overrides:
buildin classRestClient.Builder- Returns:
- The built object.
-
cache
Description copied from class:Context.BuilderSpecifies a cache to use for hashkey-based caching.When a cache is specified, contexts with the same hash key will be reused from the cache instead of creating new instances. This improves performance when building multiple contexts with identical configurations.
If
null is specified, caching is disabled and each call toContext.Builder.build()will create a new context instance.- Overrides:
cachein classRestClient.Builder- Parameters:
value- The cache.
Can benull (disables caching, each build creates a new instance).- Returns:
- This object.
-
callHandler
Description copied from class:RestClient.BuilderREST call handler class.Specifies a custom handler for making HTTP calls.
This is a shortcut for
callHandler().type( .value )- Overrides:
callHandlerin classRestClient.Builder- Parameters:
value- The new value for this setting.
Cannot benull .- Returns:
- This object.
- See Also:
-
clientVersion
Description copied from class:RestClient.BuilderSets the client version by setting the value for the"Client-Version" header.This is a shortcut for calling
headerData().append(ClientVersion. .of (value ))- Overrides:
clientVersionin classRestClient.Builder- 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
public MockRestClient.Builder connectionBackoffStrategy(ConnectionBackoffStrategy connectionBackoffStrategy) Description copied from class:RestClient.BuilderAssignsConnectionBackoffStrategyinstance.- Overrides:
connectionBackoffStrategyin classRestClient.Builder- Parameters:
connectionBackoffStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
connectionManager
Description copied from class:RestClient.BuilderAssignsHttpClientConnectionManagerinstance.- Overrides:
connectionManagerin classRestClient.Builder- Parameters:
value- New property value.
Can benull (value will not be set, a default connection manager will be created).- Returns:
- This object.
- See Also:
-
connectionReuseStrategy
Description copied from class:RestClient.BuilderAssignsConnectionReuseStrategyinstance.- Overrides:
connectionReuseStrategyin classRestClient.Builder- Parameters:
reuseStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
connectionTimeToLive
public MockRestClient.Builder connectionTimeToLive(long connTimeToLive, TimeUnit connTimeToLiveTimeUnit) Description copied from class:RestClient.BuilderSets maximum time to live for persistent connections.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
connectionTimeToLivein classRestClient.Builder- Parameters:
connTimeToLive- New property value.connTimeToLiveTimeUnit- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
console
Description copied from class:RestClient.BuilderConsole print streamAllows you to redirect the console output to a different print stream.
- Overrides:
consolein classRestClient.Builder- Parameters:
value- The new value for this setting.
Can benull (defaults toSystem.err ).- Returns:
- This object.
-
contentDecoderRegistry
public MockRestClient.Builder contentDecoderRegistry(Map<String, InputStreamFactory> contentDecoderMap) Description copied from class:RestClient.BuilderAssigns a map ofInputStreamFactoriesto be used for automatic content decompression.- Overrides:
contentDecoderRegistryin classRestClient.Builder- Parameters:
contentDecoderMap- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
contentType
Description copied from class:RestClient.BuilderSets 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.
- Overrides:
contentTypein classRestClient.Builder- Parameters:
value- The new header value.
Can benull (no Content-Type header will be added).- Returns:
- This object.
- See Also:
-
contextPath
Identifies the context path for the REST resource.This value is used to deconstruct the request URL and set the appropriate URL getters on the
HttpServletRequestobject correctly.Should either be a value such as
"/foo" or an empty string.The following fixes are applied to non-conforming strings.
nulls and"/" are converted to empty strings.- Trailing slashes are trimmed.
- Leading slash is added if needed.
- Parameters:
value- The context path.- Returns:
- This object.
-
copy
Description copied from class:Context.BuilderCopy creator.- Overrides:
copyin classRestClient.Builder- Returns:
- A new mutable copy of this builder.
-
debug
Description copied from class:RestClient.BuilderSets the value for theDebug request header on all requests.This is a shortcut for calling
headerData().append(Debug. .of (value ))- Overrides:
debugin classRestClient.Builder- Returns:
- This object.
- See Also:
-
debugOutputLines
Description copied from class:RestClient.BuilderParser 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:
- Overrides:
debugOutputLinesin classRestClient.Builder- Parameters:
value- The new value for this property.
The default value is5 .- Returns:
- This object.
-
defaultAuthSchemeRegistry
public MockRestClient.Builder defaultAuthSchemeRegistry(Lookup<AuthSchemeProvider> authSchemeRegistry) Description copied from class:RestClient.BuilderAssigns defaultAuthSchemeregistry which will be used for request execution if not explicitly set in the client execution context.- Overrides:
defaultAuthSchemeRegistryin classRestClient.Builder- Parameters:
authSchemeRegistry- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultConnectionConfig
Description copied from class:RestClient.BuilderAssigns defaultConnectionConfig.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
defaultConnectionConfigin classRestClient.Builder- Parameters:
config- 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
-
defaultCookieSpecRegistry
public MockRestClient.Builder defaultCookieSpecRegistry(Lookup<CookieSpecProvider> cookieSpecRegistry) Description copied from class:RestClient.BuilderAssigns defaultCookieSpecregistry which will be used for request execution if not explicitly set in the client execution context.- Overrides:
defaultCookieSpecRegistryin classRestClient.Builder- Parameters:
cookieSpecRegistry- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultCookieStore
Description copied from class:RestClient.BuilderAssigns defaultCookieStoreinstance which will be used for request execution if not explicitly set in the client execution context.- Overrides:
defaultCookieStorein classRestClient.Builder- Parameters:
cookieStore- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultCredentialsProvider
Description copied from class:RestClient.BuilderAssigns defaultCredentialsProviderinstance which will be used for request execution if not explicitly set in the client execution context.- Overrides:
defaultCredentialsProviderin classRestClient.Builder- Parameters:
credentialsProvider- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultRequestConfig
Description copied from class:RestClient.BuilderAssigns defaultRequestConfiginstance which will be used for request execution if not explicitly set in the client execution context.- Overrides:
defaultRequestConfigin classRestClient.Builder- Parameters:
config- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
defaultSocketConfig
Description copied from class:RestClient.BuilderAssigns defaultSocketConfig.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
defaultSocketConfigin classRestClient.Builder- Parameters:
config- 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
-
detectLeaks
Description copied from class:RestClient.BuilderRestClient 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. - Overrides:
detectLeaksin classRestClient.Builder- Returns:
- This object.
-
detectRecursions
Description copied from class:RestClient.BuilderBeanTraverse 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 asBeanRecursionExceptionwith 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:
- Overrides:
detectRecursionsin classRestClient.Builder- Returns:
- This object.
-
dictionaryOn
Description copied from class:BeanContextable.BuilderBean dictionary.This is identical to
BeanContextable.Builder.beanDictionary(Class...), but specifies a dictionary within the context of a single class as opposed to globally.Example:
// POJOs with @Bean(name) annotations. @Bean (typeName="foo" )public class Foo {...}@Bean (typeName="bar" )public class Bar {...}// A bean with a field with an indeterminate type. public class MyBean {public ObjectmySimpleField ; }// Create a parser and tell it which classes to try to resolve. ReaderParserparser = JsonParser .create () .dictionaryOn(MyBean.class , Foo.class , Bar.class ) .build();// Parse bean. MyBeanbean =parser .parse("{mySimpleField:{_type:'foo',...}}" , MyBean.class );This is functionally equivalent to the
Bean.dictionary()annotation.See Also:
- Overrides:
dictionaryOnin classRestClient.Builder- Parameters:
on- The class that the dictionary values apply to.
Cannot benull .values- The new values for this setting.
Cannot containnull values.- Returns:
- This object.
-
disableAuthCaching
Description copied from class:RestClient.BuilderDisables authentication scheme caching.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
disableAuthCachingin classRestClient.Builder- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
disableAutomaticRetries
Description copied from class:RestClient.BuilderDisables automatic request recovery and re-execution.- Overrides:
disableAutomaticRetriesin classRestClient.Builder- Returns:
- This object.
- See Also:
-
disableBeansRequireSomeProperties
Description copied from class:BeanContextable.BuilderBeans don't require at least one property.When enabled, then a Java class doesn't need to contain at least 1 property to be considered a bean. Otherwise, the bean will be serialized as a string using the
Object.toString()method.The
@Beanannotation can be used on a class to override this setting whentrue .Example:
// A bean with no properties. public class MyBean { }// Create a serializer that serializes beans even if they have zero properties. WriterSerializerserializer = JsonSerializer .create () .disableBeansRequireSomeProperties() .build();// Produces: {} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanannotation can be used on the class to force it to be recognized as a bean class even if it has no properties.
See Also:
- Overrides:
disableBeansRequireSomePropertiesin classRestClient.Builder- Returns:
- This object.
- The
-
disableConnectionState
Description copied from class:RestClient.BuilderDisables connection state tracking.- Overrides:
disableConnectionStatein classRestClient.Builder- Returns:
- This object.
- See Also:
-
disableContentCompression
Description copied from class:RestClient.BuilderDisables automatic content decompression.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
disableContentCompressionin classRestClient.Builder- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
disableCookieManagement
Description copied from class:RestClient.BuilderDisables state (cookie) management.Notes:
- This value can be overridden by the
RestClient.Builder.httpProcessor(HttpProcessor)method.
- Overrides:
disableCookieManagementin classRestClient.Builder- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
disableIgnoreMissingSetters
Description copied from class:BeanContextable.BuilderDon't silently ignore missing setters.When enabled, trying to set a value on a bean property without a setter will throw a
BeanRuntimeException. Otherwise, it will be silently ignored.Example:
// A bean with a property with a getter but not a setter. public class MyBean {public void getFoo() {return "foo" ; } }// Create a parser that throws an exception if a setter is not found but a getter is. ReaderParserparser = JsonParser .create () .disableIgnoreMissingSetters() .build();// Throws a ParseException. MyBeanbean =parser .parse("{foo:'bar'}" , MyBean.class );Notes:
- The
@BeanIgnoreannotation can also be used on getters and fields to ignore them.
See Also:
- Overrides:
disableIgnoreMissingSettersin classRestClient.Builder- Returns:
- This object.
- The
-
disableIgnoreTransientFields
Description copied from class:BeanContextable.BuilderDon't ignore transient fields.When enabled, methods and fields marked as
transient will not be ignored as bean properties.Example:
// A bean with a transient field. public class MyBean {public transient Stringfoo ="foo" ; }// Create a serializer that doesn't ignore transient fields. WriterSerializerserializer = JsonSerializer .create () .disableIgnoreTransientFields() .build();// Produces: {"foo":"foo"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Beanpannotation can also be used on transient fields to keep them from being ignored.
See Also:
- Overrides:
disableIgnoreTransientFieldsin classRestClient.Builder- Returns:
- This object.
- The
-
disableIgnoreUnknownNullBeanProperties
Description copied from class:BeanContextable.BuilderDon't ignore unknown properties with null values.When enabled, trying to set a
null value on a non-existent bean property will throw aBeanRuntimeException. Otherwise it will be silently ignored.Example:
// A bean with a single property. public class MyBean {public Stringfoo ; }// Create a parser that throws an exception on an unknown property even if the value being set is null. ReaderParserparser = JsonParser .create () .disableIgnoreUnknownNullBeanProperties() .build();// Throws a BeanRuntimeException wrapped in a ParseException on the unknown 'bar' property. MyBeanbean =parser .parse("{foo:'foo',bar:null}" , MyBean.class );See Also:
- Overrides:
disableIgnoreUnknownNullBeanPropertiesin classRestClient.Builder- Returns:
- This object.
-
disableInterfaceProxies
Description copied from class:BeanContextable.BuilderDon't use interface proxies.When enabled, interfaces will be instantiated as proxy classes through the use of an
InvocationHandlerif there is no other way of instantiating them. Otherwise, throws aBeanRuntimeException.See Also:
- Overrides:
disableInterfaceProxiesin classRestClient.Builder- Returns:
- This object.
-
disableRedirectHandling
Description copied from class:RestClient.BuilderDisables automatic redirect handling.- Overrides:
disableRedirectHandlingin classRestClient.Builder- Returns:
- This object.
- See Also:
-
errorCodes
Description copied from class:RestClient.BuilderErrors 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();- Overrides:
errorCodesin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default value isx -> x >= 400.
Cannot benull .- Returns:
- This object.
-
evictExpiredConnections
Description copied from class:RestClient.BuilderMakes 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.
- Overrides:
evictExpiredConnectionsin classRestClient.Builder- Returns:
- This object.
- See Also:
- One MUST explicitly close HttpClient with
-
evictIdleConnections
Description copied from class:RestClient.BuilderMakes 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.
- Overrides:
evictIdleConnectionsin classRestClient.Builder- Parameters:
maxIdleTime- New property value.maxIdleTimeUnit- New property value.
Cannot benull .- Returns:
- This object.
- See Also:
- One MUST explicitly close HttpClient with
-
example
Description copied from class:BeanContextable.BuilderPOJO example.Specifies an example in JSON of the specified class.
Examples are used in cases such as POJO examples in Swagger documents.
Setting applies to specified class and all subclasses.
Example:
// Create a serializer that excludes the 'foo' and 'bar' properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .example(MyBean.class ,"{foo:'bar'}" ) .build();This is a shorthand method for the following code:
builder .annotations(MarshalledAnnotation.create (pojoClass ).example(json ).build())POJO examples can also be defined on classes via the following:
- A static field annotated with
@Example. - A static method annotated with
@Examplewith zero arguments or oneBeanSessionargument. - A static method with name
example with no arguments or oneBeanSessionargument.
See Also:
- Overrides:
examplein classBeanContextable.Builder- Type Parameters:
T- The POJO class type.- Parameters:
pojoClass- The POJO class.
Cannot benull .json- The JSON 5 representation of the example.
Can benull or empty (treated as no example).- Returns:
- This object.
- A static field annotated with
-
example
Description copied from class:BeanContextable.BuilderPOJO example.Specifies an example of the specified class.
Examples are used in cases such as POJO examples in Swagger documents.
Example:
// Create a serializer that excludes the 'foo' and 'bar' properties on the MyBean class. WriterSerializerserializer = JsonSerializer .create () .example(MyBean.class ,new MyBean().setFoo("foo" ).setBar(123)) .build();This is a shorthand method for the following code:
builder .annotations(MarshalledAnnotation.create (pojoClass ).example(Json5.DEFAULT .toString(object )).build())Notes:
- Using this method assumes the serialized form of the object is the same as that produced by the default serializer. This may not be true based on settings or swaps on the constructed serializer.
POJO examples can also be defined on classes via the following:
- The
Marshalled.example()annotation on the class itself. - A static field annotated with
@Example. - A static method annotated with
@Examplewith zero arguments or oneBeanSessionargument. - A static method with name
example with no arguments or oneBeanSessionargument.
- Overrides:
examplein classBeanContextable.Builder- Type Parameters:
T- The POJO class.- Parameters:
pojoClass- The POJO class.
Cannot benull .o- An instance of the POJO class used for examples.
Can benull (will be serialized as"null" ).- Returns:
- This object.
-
executorService
public MockRestClient.Builder executorService(ExecutorService executorService, boolean shutdownOnClose) Description copied from class:RestClient.BuilderRestClient 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();- Overrides:
executorServicein classRestClient.Builder- 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.
-
findFluentSetters
Description copied from class:BeanContextable.BuilderFind fluent setters.When enabled, fluent setters are detected on beans during parsing.
Fluent setters must have the following attributes:
- Public.
- Not static.
- Take in one parameter.
- Return the bean itself.
Example:
// A bean with a fluent setter. public class MyBean {public MyBean foo(Stringvalue ) {...} }// Create a parser that finds fluent setters. ReaderParserparser = JsonParser .create () .findFluentSetters() .build();// Parse into bean using fluent setter. MyBeanbean =parser .parse("{foo:'bar'}" , MyBean.class );Notes:
- The
@Beanpannotation can also be used on methods to individually identify them as fluent setters. - The
@Bean.fluentSetters()annotation can also be used on classes to specify to look for fluent setters.
See Also:
- Overrides:
findFluentSettersin classRestClient.Builder- Returns:
- This object.
-
findFluentSetters
Description copied from class:BeanContextable.BuilderFind fluent setters.Identical to
BeanContextable.Builder.findFluentSetters()but enables it on a specific class only.Example:
// A bean with a fluent setter. public class MyBean {public MyBean foo(Stringvalue ) {...} }// Create a parser that finds fluent setters. ReaderParserparser = JsonParser .create () .findFluentSetters(MyBean.class ) .build();// Parse into bean using fluent setter. MyBeanbean =parser .parse("{foo:'bar'}" , MyBean.class );Notes:
- This method is functionally equivalent to using the
Bean.findFluentSetters()annotation.
See Also:
- Overrides:
findFluentSettersin classRestClient.Builder- Parameters:
on- The class that this applies to.
Cannot benull .- Returns:
- This object.
- This method is functionally equivalent to using the
-
formData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
formDatain classRestClient.Builder- Parameters:
parts- The form-data parameters.
Can containnull values (ignored).- Returns:
- This object.
- See Also:
-
formData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
formDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
formData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
formDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
header
Description copied from class:RestClient.BuilderAppends a header to all requests.Example:
RestClient
client = RestClient .create () .header("Foo" ,"bar" ); .build();This is a shortcut for calling
headerData().append( .name ,value )- Overrides:
headerin classRestClient.Builder- Parameters:
name- The header name.
Cannot benull .value- The header value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
header
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
headerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
headersin classRestClient.Builder- Parameters:
parts- The header to set.
Can containnull values (ignored).- Returns:
- This object.
- See Also:
-
html
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
htmlin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
htmlDoc
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
htmlDocin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
htmlStrippedDoc
Description copied from class:RestClient.BuilderConvenience method for specifying Stripped HTML DOC as the marshalling transmission media type.Same as
RestClient.Builder.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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/html+stripped" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/html+stripped" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
htmlStrippedDocin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
httpClient
Description copied from class:RestClient.BuilderSets theHttpClientto be used to handle all HTTP communications with the target server.This can be used to bypass the client created by
RestClient.Builder.createHttpClient()method.Example:
// Construct a client that uses a customized HttpClient. RestClientclient = RestClient .create () .httpClient(HttpClientBuilder.create ().build()) .build();- Overrides:
httpClientin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderSets theHttpClientBuilderthat will be used to create theHttpClientused byRestClient.This can be used to bypass the builder created by
RestClient.Builder.createHttpClientBuilder()method.Example:
// Construct a client that uses a customized HttpClientBuilder. RestClientclient = RestClient .create () .httpClientBuilder(HttpClientBuilder.create ()) .build();- Overrides:
httpClientBuilderin classRestClient.Builder- Parameters:
value- TheHttpClientBuilderthat will be used to create theHttpClientused byRestClient.
Can benull (a default builder will be created).- Returns:
- This object.
-
httpProcessor
Description copied from class:RestClient.BuilderAssignsHttpProcessorinstance.- Overrides:
httpProcessorin classRestClient.Builder- Parameters:
httpprocessor- New property value.- Returns:
- This object.
- See Also:
-
ignoreErrors
Description copied from class:RestClient.BuilderIgnore 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);- Overrides:
ignoreErrorsin classRestClient.Builder- Returns:
- This object.
-
ignoreInvocationExceptionsOnGetters
Description copied from class:BeanContextable.BuilderIgnore invocation errors on getters.When enabled, errors thrown when calling bean getter methods will silently be ignored. Otherwise, a
BeanRuntimeExceptionis thrown.Example:
// A bean with a property that throws an exception. public class MyBean {public String getFoo() {throw new RuntimeException("foo" ); } }// Create a serializer that ignores bean getter exceptions. WriterSerializerserializer = JsonSerializer .create () .ingoreInvocationExceptionsOnGetters() .build();// Exception is ignored. Stringjson =serializer .serialize(new MyBean());See Also:
- Overrides:
ignoreInvocationExceptionsOnGettersin classRestClient.Builder- Returns:
- This object.
-
ignoreInvocationExceptionsOnSetters
Description copied from class:BeanContextable.BuilderIgnore invocation errors on setters.When enabled, errors thrown when calling bean setter methods will silently be ignored. Otherwise, a
BeanRuntimeExceptionis thrown.Example:
// A bean with a property that throws an exception. public class MyBean {public void setFoo(Stringfoo ) {throw new RuntimeException("foo" ); } }// Create a parser that ignores bean setter exceptions. ReaderParserparser = JsonParser .create () .ignoreInvocationExceptionsOnSetters() .build();// Exception is ignored. MyBeanbean =parser .parse("{foo:'bar'}" , MyBean.class );See Also:
- Overrides:
ignoreInvocationExceptionsOnSettersin classRestClient.Builder- Returns:
- This object.
-
ignoreRecursions
Description copied from class:RestClient.BuilderBeanTraverse 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:
- Overrides:
ignoreRecursionsin classRestClient.Builder- Returns:
- This object.
-
ignoreUnknownBeanProperties
Description copied from class:BeanContextable.BuilderIgnore unknown properties.When enabled, trying to set a value on a non-existent bean property will silently be ignored. Otherwise, a
BeanRuntimeExceptionis thrown.Example:
// A bean with a single property. public class MyBean {public Stringfoo ; }// Create a parser that ignores missing bean properties. ReaderParserparser = JsonParser .create () .ignoreUnknownBeanProperties() .build();// Doesn't throw an exception on unknown 'bar' property. MyBeanbean =parser .parse("{foo:'foo',bar:'bar'}" , MyBean.class );See Also:
- Overrides:
ignoreUnknownBeanPropertiesin classRestClient.Builder- Returns:
- This object.
-
ignoreUnknownEnumValues
Description copied from class:BeanContextable.BuilderIgnore unknown enum values.When enabled, unknown enum values are set to
null instead of throwing a parse exception.See Also:
- Overrides:
ignoreUnknownEnumValuesin classRestClient.Builder- Returns:
- This object.
-
impl
Description copied from class:Context.BuilderSpecifies a pre-instantiated bean for theContext.Builder.build()method to return.If a non-null value is provided and it's an instance of the context type,
Context.Builder.build()will return that instance instead of creating a new one. Ifnull , the normal build process continues.- Overrides:
implin classRestClient.Builder- Parameters:
value- The value for this setting.
Can benull (normal build process will continue).- Returns:
- This object.
-
implClass
Description copied from class:BeanContextable.BuilderImplementation classes.For interfaces and abstract classes this method can be used to specify an implementation class for the interface/abstract class so that instances of the implementation class are used when instantiated (e.g. during a parse).
Example:
// A bean interface. public interface MyBean { ... }// A bean implementation. public class MyBeanImplimplements MyBean { ... }// Create a parser that instantiates MyBeanImpls when parsing MyBeans. ReaderParserparser = JsonParser .create () .implClass(MyBean.class , MyBeanImpl.class ) .build();// Instantiates a MyBeanImpl, MyBeanbean =parser .parse("..." , MyBean.class );- Overrides:
implClassin classRestClient.Builder- Parameters:
interfaceClass- The interface class.
Cannot benull .implClass- The implementation class.
Cannot benull .- Returns:
- This object.
-
implClasses
Description copied from class:BeanContextable.BuilderImplementation classes.For interfaces and abstract classes this method can be used to specify an implementation class for the interface/abstract class so that instances of the implementation class are used when instantiated (e.g. during a parse).
Example:
// A bean with a single property. public interface MyBean { ... }// A bean with a single property. public class MyBeanImplimplements MyBean { ... }// Create a parser that instantiates MyBeanImpls when parsing MyBeans. ReaderParserparser = JsonParser .create () .implClasses(AMap.of (MyBean.class , MyBeanImpl.class )) .build();// Instantiates a MyBeanImpl, MyBeanbean =parser .parse("..." , MyBean.class );- Overrides:
implClassesin classRestClient.Builder- Parameters:
values- The new value for this setting.
Cannot benull .- Returns:
- This object.
-
initialDepth
Description copied from class:RestClient.BuilderBeanTraverse 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:
- Overrides:
initialDepthin classRestClient.Builder- Parameters:
value- The new value for this property.
The default is0 .- Returns:
- This object.
-
interceptors
Description copied from class:RestClient.BuilderRestClient 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.
- Overrides:
interceptorsin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderCall 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.
- Overrides:
interceptorsin classRestClient.Builder- 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
-
interfaceClass
Description copied from class:BeanContextable.BuilderIdentifies a class to be used as the interface class for the specified class and all subclasses.When specified, only the list of properties defined on the interface class will be used during serialization. Additional properties on subclasses will be ignored.
// Parent class or interface public abstract class A {public Stringfoo ="foo" ; }// Sub class public class A1extends A {public Stringbar ="bar" ; }// Create a serializer and define our interface class mapping. WriterSerializerserializer = JsonSerializer .create () .interfaceClass(A1.class , A.class ) .build();// Produces "{"foo":"foo"}" Stringjson =serializer .serialize(new A1());This annotation can be used on the parent class so that it filters to all child classes, or can be set individually on the child classes.
Notes:
- The
@Bean(interfaceClass)annotation is the equivalent annotation-based solution.
- Overrides:
interfaceClassin classRestClient.Builder- Parameters:
on- The class that the interface class applies to.
Cannot benull .value- The new value for this setting.
Cannot benull .- Returns:
- This object.
- The
-
interfaces
Description copied from class:BeanContextable.BuilderIdentifies a set of interfaces.When specified, only the list of properties defined on the interface class will be used during serialization of implementation classes. Additional properties on subclasses will be ignored.
// Parent class or interface public abstract class A {public Stringfoo ="foo" ; }// Sub class public class A1extends A {public Stringbar ="bar" ; }// Create a serializer and define our interface class mapping. WriterSerializerserializer = JsonSerializer .create () .interfaces(A.class ) .build();// Produces "{"foo":"foo"}" Stringjson =serializer .serialize(new A1());This annotation can be used on the parent class so that it filters to all child classes, or can be set individually on the child classes.
Notes:
- The
@Bean(interfaceClass)annotation is the equivalent annotation-based solution.
- Overrides:
interfacesin classRestClient.Builder- Parameters:
value- The new value for this setting.
Cannot containnull values.- Returns:
- This object.
- The
-
json
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/json" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header)}.Content-Type request header will be set to"application/json" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
jsonin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
json5
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/json" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"application/json5" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
json5in classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
keepAliveStrategy
Description copied from class:RestClient.BuilderAssignsConnectionKeepAliveStrategyinstance.- Overrides:
keepAliveStrategyin classRestClient.Builder- Parameters:
keepAliveStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
keepHttpClientOpen
Description copied from class:RestClient.BuilderRestClient 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. - Overrides:
keepHttpClientOpenin classRestClient.Builder- Returns:
- This object.
-
keepNullProperties
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
keepNullPropertiesin classRestClient.Builder- Returns:
- This object.
- Not enabling this setting will cause
-
locale
Description copied from class:BeanContextable.BuilderContext configuration property: Locale.Specifies the default locale for serializer and parser sessions when not specified via
BeanSession.Builder.locale(Locale). Typically used for POJO swaps that need to deal with locales such as swaps that convertDate andCalendar objects to strings by accessing it via the session passed into theObjectSwap.swap(BeanSession, Object)andObjectSwap.unswap(BeanSession, Object, ClassMeta, String)methods.Example:
// Define a POJO swap that skips serializing beans if we're in the UK. public class MyBeanSwapextends StringSwap<MyBean> {@Override public String swap(BeanSessionsession , MyBeanbean )throws Exception {if (session .getLocale().equals(Locale.UK ))return null ;return bean .toString(); } }// Create a serializer that uses the specified locale if it's not passed in through session args. WriterSerializerserializer = JsonSerializer .create () .locale(Locale.UK ) .swaps(MyBeanSwap.class ) .build();See Also:
- Overrides:
localein classRestClient.Builder- Parameters:
value- The new value for this property.
Cannot benull .- Returns:
- This object.
-
logger
Description copied from class:RestClient.BuilderLogger.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();- Overrides:
loggerin classRestClient.Builder- Parameters:
value- The logger to use for logging.
Can benull (defaults toLogger.getLogger(RestClient.class.getName()) ).- Returns:
- This object.
-
logRequests
public MockRestClient.Builder logRequests(DetailLevel detail, Level level, BiPredicate<RestRequest, RestResponse> test) Description copied from class:RestClient.BuilderLog 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
RestClient.Builder.logger(Logger)method or logged to the console using theRestClient.Builder.logToConsole()method.- Overrides:
logRequestsin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderLog 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();- Overrides:
logToConsolein classRestClient.Builder- Returns:
- This object.
-
marshaller
Description copied from class:RestClient.BuilderRestClient 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.
RestClient.Builder.sortCollections()), parser property setters (e.g.RestClient.Builder.strict()), or bean context property setters (e.g.RestClient.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();- Overrides:
marshallerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderRestClient 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.
RestClient.Builder.sortCollections()), parser property setters (e.g.RestClient.Builder.strict()), or bean context property setters (e.g.RestClient.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();- Overrides:
marshallersin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderAssigns maximum connection per route value.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
maxConnPerRoutein classRestClient.Builder- Parameters:
maxConnPerRoute- New property value.- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
maxConnTotal
Description copied from class:RestClient.BuilderAssigns maximum total connection value.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
maxConnTotalin classRestClient.Builder- Parameters:
maxConnTotal- New property value.- Returns:
- This object.
- See Also:
- This value can be overridden by the
-
maxDepth
Description copied from class:RestClient.BuilderBeanTraverse 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:
- Overrides:
maxDepthin classRestClient.Builder- Parameters:
value- The new value for this property.
The default is100 .- Returns:
- This object.
-
maxIndent
Description copied from class:RestClient.BuilderWriterSerializer 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:
- Overrides:
maxIndentin classRestClient.Builder- Parameters:
value- The new value for this property.
The default is100 .- Returns:
- This object.
-
mediaType
Description copied from class:RestClient.BuilderAppends 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 classRestClient.Builder- Parameters:
value- The new header values.
Can benull (no Accept or Content-Type headers will be added).- Returns:
- This object.
- See Also:
-
mediaType
Description copied from class:RestClient.BuilderAppends 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 classRestClient.Builder- Parameters:
value- The new header values.
Can benull (no Accept or Content-Type headers will be added).- Returns:
- This object.
- See Also:
-
msgPack
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"octal/msgpack" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"octal/msgpack" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
msgPackin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
notBeanClasses
Description copied from class:BeanContextable.BuilderBean class exclusions.List of classes that should not be treated as beans even if they appear to be bean-like. Not-bean classes are converted to
Strings during serialization.Values can consist of any of the following types:
- Classes.
- Arrays and collections of classes.
Example:
// A bean with a single property. public class MyBean {public Stringfoo ="bar" ;public String toString() {return "baz" ; } }// Create a serializer that doesn't treat MyBean as a bean class. WriterSerializerserializer = JsonSerializer .create () .notBeanClasses(MyBean.class ) .build();// Produces "baz" instead of {"foo":"bar"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@BeanIgnoreannotation can also be used on classes to prevent them from being recognized as beans.
See Also:
- Overrides:
notBeanClassesin classRestClient.Builder- Parameters:
values- The values to add to this setting.
Values can consist of any of the following types:- Classes.
- Arrays and collections of classes.
Cannot containnull values.- Returns:
- This object.
-
notBeanPackages
Description copied from class:BeanContextable.BuilderBean package exclusions.Used as a convenient way of defining the
BeanContext.Builder.notBeanClasses(Class...)property for entire packages. Any classes within these packages will be serialized to strings usingObject.toString().Note that you can specify suffix patterns to include all subpackages.
Values can consist of any of the following types:
- Strings.
- Arrays and collections of strings.
Example:
// Create a serializer that ignores beans in the specified packages. WriterSerializerserializer = JsonSerializer .create () .notBeanPackages("org.apache.foo" ,"org.apache.bar.*" ) .build();See Also:
- Overrides:
notBeanPackagesin classRestClient.Builder- Parameters:
values- The values to add to this setting.
Values can consist of any of the following types:Packageobjects.- Strings.
- Arrays and collections of anything in this list.
Cannot containnull values.- Returns:
- This object.
-
noTrace
Description copied from class:RestClient.BuilderWhen 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.- Overrides:
noTracein classRestClient.Builder- Returns:
- This object.
- See Also:
-
oapiCollectionFormat
Description copied from class:RestClient.BuilderOpenApiCommon 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:
- Overrides:
oapiCollectionFormatin classRestClient.Builder- Parameters:
value- The new value for this property.
The default value isHttpPartCollectionFormat.NO_COLLECTION_FORMAT.
Cannot benull .- Returns:
- This object.
-
oapiFormat
Description copied from class:RestClient.BuilderOpenApiCommon 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:
- Overrides:
oapiFormatin classRestClient.Builder- Parameters:
value- The new value for this property.
The default value isHttpPartFormat.NO_FORMAT.
Cannot benull .- Returns:
- This object.
-
openApi
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.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 viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/openapi" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
openApiin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
paramFormat
Description copied from class:RestClient.BuilderUonSerializer 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:
- Overrides:
paramFormatin classRestClient.Builder- Parameters:
value- The new value for this property.
Cannot benull .- Returns:
- This object.
-
paramFormatPlain
Description copied from class:RestClient.BuilderUonSerializer 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:
- Overrides:
paramFormatPlainin classRestClient.Builder- Returns:
- This object.
-
parser
Description copied from class:RestClient.BuilderParser.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.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 ) .strict()// Enable strict mode on JsonParser. .build();- Overrides:
parserin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderParser.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.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_STRICT ) .build();- Overrides:
parserin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderParsers.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.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 ) .strict()// Enable strict mode on parsers. .build();- Overrides:
parsersin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderParsers.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.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_STRICT , XmlParser.DEFAULT ) .build();- Overrides:
parsersin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderPart 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();- Overrides:
partParserin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default value isOpenApiParser.
Cannot benull .- Returns:
- This object.
-
partParser
Description copied from class:RestClient.BuilderPart 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();- Overrides:
partParserin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default value isOpenApiParser.
Cannot benull .- Returns:
- This object.
-
partSerializer
Description copied from class:RestClient.BuilderPart 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();- Overrides:
partSerializerin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default value isOpenApiSerializer.
Cannot benull .- Returns:
- This object.
-
partSerializer
Description copied from class:RestClient.BuilderPart 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();- Overrides:
partSerializerin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default value isOpenApiSerializer.
Cannot benull .- Returns:
- This object.
-
pathData
Description copied from class:RestClient.BuilderSets 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 )- Overrides:
pathDatain classRestClient.Builder- Parameters:
parts- The path parameters.
Can containnull values (ignored).- Returns:
- This object.
- See Also:
-
pathData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
pathDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
pathData
Description copied from class:RestClient.BuilderSets 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 )- Overrides:
pathDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
pathVars
Add resolved path variables to this client.Allows you to add resolved parent path variables when performing tests on child resource classes.
Example:
// A parent class with a path variable. @Rest ( path="/parent/{foo}" , children={ Child.class } )public class Parent { ... }// A child class that uses the parent path variable. @Rest public class Child {@RestGet public String get(@Path ("foo" ) Stringfoo ) {return foo ; } }// Test the method that uses the parent path variable. MockRestClient .create (Child.class ) .json5() .pathVars("foo" ,"bar" ) .build() .get("/" ) .run() .assertStatus().asCode().is(200) .assertContent().is("bar" );Needs review - Parameters:
value- The path variables.- Returns:
- This object.
- See Also:
-
pathVars
Add resolved path variables to this client.Identical to
pathVars(Map)but allows you to specify as a list of key/value pairs.- Parameters:
pairs- The key/value pairs. Must be an even number of parameters.- Returns:
- This object.
-
plainText
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/plain" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/plain" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
plainTextin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
pooled
Description copied from class:RestClient.BuilderWhen called, theRestClient.Builder.createConnectionManager()method will return aPoolingHttpClientConnectionManagerinstead of aBasicHttpClientConnectionManager.Example:
// Construct a client that uses pooled connections. RestClientclient = RestClient .create () .pooled() .build();- Overrides:
pooledin classRestClient.Builder- Returns:
- This object.
-
propertyNamer
Description copied from class:BeanContextable.BuilderBean property namerSame as
BeanContextable.Builder.propertyNamer(Class)but allows you to specify a namer for a specific class.Example:
// A bean with a single property. public class MyBean {public StringfooBarBaz ="fooBarBaz" ; }// Create a serializer that uses Dashed-Lower-Case property names for the MyBean class only. // (e.g. "foo-bar-baz" instead of "fooBarBaz") WriterSerializerserializer = JsonSerializer .create () .propertyNamer(MyBean.class , PropertyNamerDLC.class ) .build();// Produces: {"foo-bar-baz":"fooBarBaz"} Stringjson =serializer .serialize(new MyBean());See Also:
- Overrides:
propertyNamerin classRestClient.Builder- Parameters:
on- The class that the namer applies to.
Cannot benull .value- The new value for this setting.
The default isBasicPropertyNamer.
Cannot benull .- Returns:
- This object.
-
propertyNamer
Description copied from class:BeanContextable.BuilderBean property namerThe class to use for calculating bean property names.
Predefined classes:
BasicPropertyNamer- Default.PropertyNamerDLC- Dashed-lower-case names.PropertyNamerULC- Dashed-upper-case names.
Example:
// A bean with a single property. public class MyBean {public StringfooBarBaz ="fooBarBaz" ; }// Create a serializer that uses Dashed-Lower-Case property names. // (e.g. "foo-bar-baz" instead of "fooBarBaz") WriterSerializerserializer = JsonSerializer .create () .propertyNamer(PropertyNamerDLC.class ) .build();// Produces: {"foo-bar-baz":"fooBarBaz"} Stringjson =serializer .serialize(new MyBean());See Also:
- Overrides:
propertyNamerin classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isBasicPropertyNamer.
Cannot benull .- Returns:
- This object.
-
proxy
Description copied from class:RestClient.BuilderAssigns default proxy value.Notes:
- This value can be overridden by the
RestClient.Builder.routePlanner(HttpRoutePlanner)method.
- Overrides:
proxyin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderAssignsAuthenticationStrategyinstance for proxy authentication.- Overrides:
proxyAuthenticationStrategyin classRestClient.Builder- Parameters:
proxyAuthStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
publicSuffixMatcher
Description copied from class:RestClient.BuilderAssigns file containing public suffix matcher.Notes:
- Instances of this class can be created with
PublicSuffixMatcherLoader.
- Overrides:
publicSuffixMatcherin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
queryDatain classRestClient.Builder- Parameters:
parts- The query parameters.
Can containnull values (ignored).- Returns:
- This object.
- See Also:
-
queryData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
queryDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
queryData
Description copied from class:RestClient.BuilderAppends 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 )- Overrides:
queryDatain classRestClient.Builder- Parameters:
name- The parameter name.
Cannot benull .value- The parameter value supplier.
Can benull (null value will be serialized).- Returns:
- This object.
- See Also:
-
quoteChar
Description copied from class:RestClient.BuilderWriterSerializer 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:
- Overrides:
quoteCharin classRestClient.Builder- Parameters:
value- The new value for this property.
The default is'"' .- Returns:
- This object.
-
redirectStrategy
Description copied from class:RestClient.BuilderAssignsRedirectStrategyinstance.Notes:
- This value can be overridden by the
RestClient.Builder.disableRedirectHandling()method.
- Overrides:
redirectStrategyin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderAssignsHttpRequestExecutorinstance.- Overrides:
requestExecutorin classRestClient.Builder- Parameters:
requestExec- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
restBean
Specifies theRest-annotated bean class or instance to test against.- Parameters:
value- TheRest-annotated bean class or instance.- Returns:
- This object.
-
restContext
Specifies theRestContextcreated for the REST bean.- Parameters:
value- TheRestContextcreated for the REST bean.- Returns:
- This object.
-
retryHandler
Description copied from class:RestClient.BuilderAssignsHttpRequestRetryHandlerinstance.Notes:
- This value can be overridden by the
RestClient.Builder.disableAutomaticRetries()method.
- Overrides:
retryHandlerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderRestClient 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 );- Overrides:
rootUrlin classRestClient.Builder- 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.
-
routePlanner
Description copied from class:RestClient.BuilderAssignsHttpRoutePlannerinstance.- Overrides:
routePlannerin classRestClient.Builder- Parameters:
routePlanner- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
schemePortResolver
Description copied from class:RestClient.BuilderAssignsSchemePortResolverinstance.- Overrides:
schemePortResolverin classRestClient.Builder- Parameters:
schemePortResolver- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
serializer
Description copied from class:RestClient.BuilderSerializer.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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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();- Overrides:
serializerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderSerializer.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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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();- Overrides:
serializerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderSerializers.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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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();- Overrides:
serializersin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderSerializers.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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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();- Overrides:
serializersin classRestClient.Builder- 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.
-
servletPath
Identifies the servlet path for the REST resource.This value is used to deconstruct the request URL and set the appropriate URL getters on the
HttpServletRequestobject correctly.Should either be a value such as
"/foo" or an empty string.The following fixes are applied to non-conforming strings.
nulls and"/" are converted to empty strings.- Trailing slashes are trimmed.
- Leading slash is added if needed.
- Parameters:
value- The context path.- Returns:
- This object.
-
skipEmptyFormData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyFormDatain classRestClient.Builder- Returns:
- This object.
-
skipEmptyFormData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyFormDatain classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isfalse .- Returns:
- This object.
-
skipEmptyHeaderData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyHeaderDatain classRestClient.Builder- Returns:
- This object.
-
skipEmptyHeaderData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyHeaderDatain classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isfalse .- Returns:
- This object.
-
skipEmptyQueryData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyQueryDatain classRestClient.Builder- Returns:
- This object.
-
skipEmptyQueryData
Description copied from class:RestClient.BuilderSkip 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.- Overrides:
skipEmptyQueryDatain classRestClient.Builder- Parameters:
value- The new value for this setting.
The default isfalse .- Returns:
- This object.
-
sortCollections
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
sortCollectionsin classRestClient.Builder- Returns:
- This object.
-
sortMaps
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
sortMapsin classRestClient.Builder- Returns:
- This object.
-
sortProperties
Description copied from class:BeanContextable.BuilderSort bean properties.When enabled, all bean properties will be serialized and access in alphabetical order. Otherwise, the natural order of the bean properties is used which is dependent on the JVM vendor. On IBM JVMs, the bean properties are ordered based on their ordering in the Java file. On Oracle JVMs, the bean properties are not ordered (which follows the official JVM specs).
this setting is disabled by default so that IBM JVM users don't have to use
@Beanannotations to force bean properties to be in a particular order and can just alter the order of the fields/methods in the Java file.Example:
// A bean with 3 properties. public class MyBean {public Stringc ="1" ;public Stringb ="2" ;public Stringa ="3" ; }// Create a serializer that sorts bean properties. WriterSerializerserializer = JsonSerializer .create () .sortProperties() .build();// Produces: {"a":"3","b":"2","c":"1"} Stringjson =serializer .serialize(new MyBean());Notes:
- The
@Bean.sort()annotation can also be used to sort properties on just a single class.
See Also:
- Overrides:
sortPropertiesin classRestClient.Builder- Returns:
- This object.
- The
-
sortProperties
Description copied from class:BeanContextable.BuilderSort bean properties.Same as
BeanContextable.Builder.sortProperties()but allows you to specify individual bean classes instead of globally.Example:
// A bean with 3 properties. public class MyBean {public Stringc ="1" ;public Stringb ="2" ;public Stringa ="3" ; }// Create a serializer that sorts properties on MyBean. WriterSerializerserializer = JsonSerializer .create () .sortProperties(MyBean.class ) .build();// Produces: {"a":"3","b":"2","c":"1"} Stringjson =serializer .serialize(new MyBean());See Also:
- Overrides:
sortPropertiesin classRestClient.Builder- Parameters:
on- The bean classes to sort properties on.
Cannot containnull values.- Returns:
- This object.
-
sq
Description copied from class:RestClient.BuilderWriterSerializer 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:
- Overrides:
sqin classRestClient.Builder- Returns:
- This object.
-
sslContext
Description copied from class:RestClient.BuilderAssignsSSLContextinstance.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)and theRestClient.Builder.sslSocketFactory(LayeredConnectionSocketFactory)methods.
- Overrides:
sslContextin classRestClient.Builder- Parameters:
sslContext- 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
-
sslHostnameVerifier
Description copied from class:RestClient.BuilderAssignsHostnameVerifierinstance.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)and theRestClient.Builder.sslSocketFactory(LayeredConnectionSocketFactory)methods.
- Overrides:
sslHostnameVerifierin classRestClient.Builder- Parameters:
hostnameVerifier- 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
-
sslSocketFactory
Description copied from class:RestClient.BuilderAssignsLayeredConnectionSocketFactoryinstance.Notes:
- This value can be overridden by the
RestClient.Builder.connectionManager(HttpClientConnectionManager)method.
- Overrides:
sslSocketFactoryin classRestClient.Builder- Parameters:
sslSocketFactory- 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
-
stopClass
Description copied from class:BeanContextable.BuilderIdentifies a stop class for the annotated class.Identical in purpose to the stop class specified by
Introspector.getBeanInfo(Class, Class). Any properties in the stop class or in its base classes will be ignored during analysis.For example, in the following class hierarchy, instances of
C3 will include propertyp3 , but notp1 orp2 .Example:
public class C1 {public int getP1(); }public class C2extends C1 {public int getP2(); }public class C3extends C2 {public int getP3(); }// Create a serializer specifies a stop class for C3. WriterSerializerserializer = JsonSerializer .create () .stopClass(C3.class , C2.class ) .build();// Produces: {"p3":"..."} Stringjson =serializer .serialize(new C3());- Overrides:
stopClassin classRestClient.Builder- Parameters:
on- The class on which the stop class is being applied.
Cannot benull .value- The new value for this setting.
Cannot benull .- Returns:
- This object.
-
strict
Description copied from class:RestClient.BuilderParser configuration property: Strict mode.When enabled, strict mode for the parser is enabled.
Strict mode can mean different things for different parsers.
Parser class Strict behavior All reader-based parsers When enabled, throws ParseExceptionson malformed charset input. Otherwise, malformed input is ignored.JsonParserWhen enabled, throws exceptions on the following invalid JSON syntax: - Unquoted attributes.
- Missing attribute values.
- Concatenated strings.
- Javascript comments.
- Numbers and booleans when Strings are expected.
- Numbers valid in Java but not JSON (e.g. octal notation, etc...)
Example:
// Create a REST client with JSON parser using strict mode. RestClientclient = RestClient .create () .json() .strict() .build();// Try to parse some bad JSON. try {client .get("/pathToBadJson" ) .run() .getContent().as(Object.class );// Try to parse it. }catch (RestCallExceptione ) {// Handle exception. }See Also:
- Overrides:
strictin classRestClient.Builder- Returns:
- This object.
-
suppressLogging
Suppress logging on this client.- Returns:
- This object.
-
swap
public <T,S> MockRestClient.Builder swap(Class<T> normalClass, Class<S> swappedClass, ThrowingFunction<T, S> swapFunction) Description copied from class:BeanContextable.BuilderA shortcut for defining aFunctionalSwap.Example:
// Create a serializer that performs a custom format for Date objects. WriterSerializerserializer = JsonSerializer .create () .swap(Date.class , String.class ,x ->format (x )) .build();- Overrides:
swapin classRestClient.Builder- Type Parameters:
T- The object type being swapped out.S- The object type being swapped in.- Parameters:
normalClass- The object type being swapped out.
Cannot benull .swappedClass- The object type being swapped in.
Cannot benull .swapFunction- The function to convert the object.
Cannot benull .- Returns:
- This object.
-
swap
public <T,S> MockRestClient.Builder swap(Class<T> normalClass, Class<S> swappedClass, ThrowingFunction<T, S> swapFunction, ThrowingFunction<S, T> unswapFunction) Description copied from class:BeanContextable.BuilderA shortcut for defining aFunctionalSwap.Example:
// Create a serializer that performs a custom format for Date objects. WriterSerializerserializer = JsonSerializer .create () .swap(Date.class , String.class ,x ->format (x ),x ->parse (x )) .build();- Overrides:
swapin classRestClient.Builder- Type Parameters:
T- The object type being swapped out.S- The object type being swapped in.- Parameters:
normalClass- The object type being swapped out.
Cannot benull .swappedClass- The object type being swapped in.
Cannot benull .swapFunction- The function to convert the object during serialization.
Cannot benull .unswapFunction- The function to convert the object during parsing.
Cannot benull .- Returns:
- This object.
-
swaps
Description copied from class:BeanContextable.BuilderSame asBeanContextable.Builder.swaps(Object...)except explicitly specifies class varargs to avoid compilation warnings.- Overrides:
swapsin classRestClient.Builder- Parameters:
values- The values to add to this setting.
Values can consist of any of the following types:- Any subclass of
ObjectSwap. - Any surrogate class. A shortcut for defining a
SurrogateSwap.
Cannot containnull values.- Any subclass of
- Returns:
- This object.
-
swaps
Description copied from class:BeanContextable.BuilderJava object swaps.Swaps are used to "swap out" non-serializable classes with serializable equivalents during serialization, and "swap in" the non-serializable class during parsing.
An example of a swap would be a
Calendar object that gets swapped out for an ISO8601 string.Multiple swaps can be associated with a single class. When multiple swaps are applicable to the same class, the media type pattern defined by
ObjectSwap.forMediaTypes()or@Swap(mediaTypes)are used to come up with the best match.Values can consist of any of the following types:
- Any subclass of
ObjectSwap. - Any instance of
ObjectSwap. - Any surrogate class. A shortcut for defining a
SurrogateSwap. - Any array or collection of the objects above.
Example:
// Sample swap for converting Dates to ISO8601 strings. public class MyDateSwapextends StringSwap<Date> {// ISO8601 formatter. private DateFormatformat =new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ" );@Override public String swap(BeanSessionsession , Datedate ) {return format .format(date ); }@Override public Date unswap(BeanSessionsession , Stringstring , ClassMetahint )throws Exception {return format .parse(string ); } }// Sample bean with a Date field. public class MyBean {public Datedate =new Date(112, 2, 3, 4, 5, 6); }// Create a serializer that uses our date swap. WriterSerializerserializer = JsonSerializer .create () .swaps(MyDateSwap.class ) .build();// Produces: {"date":"2012-03-03T04:05:06-0500"} Stringjson =serializer .serialize(new MyBean());// Create a serializer that uses our date swap. ReaderParserparser = JsonParser .create () .swaps(MyDateSwap.class ) .build();// Use our parser to parse a bean. MyBeanbean =parser .parse(json , MyBean.class );Notes:
- The
@Swapannotation can also be used on classes to identify swaps for the class. - The
@Swapannotation can also be used on bean methods and fields to identify swaps for values of those bean properties.
See Also:
- Overrides:
swapsin classRestClient.Builder- Parameters:
values- The values to add to this setting.
Values can consist of any of the following types:- Any subclass of
ObjectSwap. - Any surrogate class. A shortcut for defining a
SurrogateSwap. - Any array/collection/stream of the objects above.
Cannot containnull values.- Any subclass of
- Returns:
- This object.
- Any subclass of
-
targetAuthenticationStrategy
public MockRestClient.Builder targetAuthenticationStrategy(AuthenticationStrategy targetAuthStrategy) Description copied from class:RestClient.BuilderAssignsAuthenticationStrategyinstance for target host authentication.- Overrides:
targetAuthenticationStrategyin classRestClient.Builder- Parameters:
targetAuthStrategy- New property value.
Can benull (value will not be set, default behavior will be used).- Returns:
- This object.
- See Also:
-
timeZone
Description copied from class:BeanContextable.BuilderContext configuration property: TimeZone.Specifies the default time zone for serializer and parser sessions when not specified via
BeanSession.Builder.timeZone(TimeZone). Typically used for POJO swaps that need to deal with timezones such as swaps that convertDate andCalendar objects to strings by accessing it via the session passed into theObjectSwap.swap(BeanSession, Object)andObjectSwap.unswap(BeanSession, Object, ClassMeta, String)methods.Example:
// Define a POJO swap that skips serializing beans if the time zone is GMT. public class MyBeanSwapextends StringSwap<MyBean> {@Override public String swap(BeanSessionsession , MyBeanbean )throws Exception {if (session .getTimeZone().equals(TimeZone.GMT ))return null ;return bean .toString(); } }// Create a serializer that uses GMT if the timezone is not specified in the session args. WriterSerializerserializer = JsonSerializer .create () .timeZone(TimeZone.GMT ) .build();See Also:
- Overrides:
timeZonein classRestClient.Builder- Parameters:
value- The new value for this property.
Can benull (timezone will not be set, defaults to system timezone).- Returns:
- This object.
-
trimEmptyCollections
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
trimEmptyCollectionsin classRestClient.Builder- Returns:
- This object.
-
trimEmptyMaps
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
trimEmptyMapsin classRestClient.Builder- Returns:
- This object.
-
trimStringsOnRead
Description copied from class:RestClient.BuilderParser 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:
- Overrides:
trimStringsOnReadin classRestClient.Builder- Returns:
- This object.
-
trimStringsOnWrite
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
trimStringsOnWritein classRestClient.Builder- Returns:
- This object.
-
type
Description copied from class:Context.BuilderAssociates a context class with this builder.This is the type of object that this builder creates when the
Context.Builder.build()method is called.By default, it's the outer class of where the builder class is defined.
If
null is set,Context.Builder.build()will throw an exception. The default constructor automatically sets this to the outer class, sonull should only be set explicitly if you want to override the default.- Overrides:
typein classRestClient.Builder- Parameters:
value- The context class that this builder should create.
Can benull (will causeContext.Builder.build()to throw an exception).- Returns:
- This object.
-
typeName
Description copied from class:BeanContextable.BuilderAn identifying name for this class.The name is used to identify the class type during parsing when it cannot be inferred through reflection. For example, if a bean property is of type
Object , then the serializer will add the name to the output so that the class can be determined during parsing.It is also used to specify element names in XML.
Example:
// Use _type='mybean' to identify this bean. public class MyBean {...}// Create a serializer and specify the type name.. WriterSerializerserializer = JsonSerializer .create () .typeName(MyBean.class ,"mybean" ) .build();// Produces: {"_type":"mybean",...} Stringjson =serializer .serialize(new MyBean());Notes:
- Equivalent to the
Bean(typeName)annotation.
See Also:
- Overrides:
typeNamein classRestClient.Builder- Parameters:
on- The class the type name is being defined on.value- The new value for this setting.
Cannot benull .- Returns:
- This object.
- Equivalent to the
-
typePropertyName
Description copied from class:BeanContextable.BuilderBean type property name.Same as
BeanContextable.Builder.typePropertyName(String)except targets a specific bean class instead of globally.Example:
// POJOs with @Bean(name) annotations. @Bean (typeName="foo" )public class Foo {...}@Bean (typeName="bar" )public class Bar {...}// A bean with a field with an indeterminate type. public class MyBean {public ObjectmySimpleField ; }// Create a serializer that uses 't' instead of '_type' for dictionary names. WriterSerializerserializer = JsonSerializer .create () .typePropertyName(MyBean.class ,"t" ) .dictionary(Foo.class , Bar.class ) .build();// Produces "{mySimpleField:{t:'foo',...}}". Stringjson =serializer .serialize(new MyBean());See Also:
- Overrides:
typePropertyNamein classRestClient.Builder- Parameters:
on- The class the type property name applies to.value- The new value for this setting.
The default is"_type" .
Cannot benull .- Returns:
- This object.
-
typePropertyName
Description copied from class:BeanContextable.BuilderBean type property name.This specifies the name of the bean property used to store the dictionary name of a bean type so that the parser knows the data type to reconstruct.
Example:
// POJOs with @Bean(name) annotations. @Bean (typeName="foo" )public class Foo {...}@Bean (typeName="bar" )public class Bar {...}// Create a serializer that uses 't' instead of '_type' for dictionary names. WriterSerializerserializer = JsonSerializer .create () .typePropertyName("t" ) .dictionary(Foo.class , Bar.class ) .build();// Create a serializer that uses 't' instead of '_type' for dictionary names. ReaderParserparser = JsonParser .create () .typePropertyName("t" ) .dictionary(Foo.class , Bar.class ) .build();// A bean with a field with an indeterminate type. public class MyBean {public ObjectmySimpleField ; }// Produces "{mySimpleField:{t:'foo',...}}". Stringjson =serializer .serialize(new MyBean());// Parse bean. MyBeanbean =parser .parse(json , MyBean.class );See Also:
- Overrides:
typePropertyNamein classRestClient.Builder- Parameters:
value- The new value for this setting.
The default is"_type" .
Cannot benull .- Returns:
- This object.
-
uon
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/uon" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/uon" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
uonin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
uriContext
Description copied from class:RestClient.BuilderSerializer 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:
- Overrides:
uriContextin classRestClient.Builder- Parameters:
value- The new value for this property.
Cannot benull .- Returns:
- This object.
-
uriRelativity
Description copied from class:RestClient.BuilderSerializer configuration property: URI relativity.Defines what relative URIs are relative to when serializing any of the following:
See
RestClient.Builder.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:
- Overrides:
uriRelativityin classRestClient.Builder- Parameters:
value- The new value for this property.
The default isUriRelativity.RESOURCE
Cannot benull .- Returns:
- This object.
-
uriResolution
Description copied from class:RestClient.BuilderSerializer configuration property: URI resolution.Defines the resolution level for URIs when serializing any of the following:
See
RestClient.Builder.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:
- Overrides:
uriResolutionin classRestClient.Builder- Parameters:
value- The new value for this property.
The default isUriResolution.NONE
Cannot benull .- Returns:
- This object.
-
urlEnc
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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 viaRestClient.Builder.partSerializer(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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"application/x-www-form-urlencoded" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"application/x-www-form-urlencoded" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
urlEncin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-
useEnumNames
Description copied from class:BeanContextable.BuilderUse enum names.When enabled, enums are always serialized by name, not using
Object.toString().Example:
// Create a serializer with debug enabled. WriterSerializerserializer = JsonSerializer .create () .useEnumNames() .build();// Enum with overridden toString(). // Will be serialized as ONE/TWO/THREE even though there's a toString() method. public enum Option {ONE (1),TWO (2),THREE (3);private int value ; Option(int value ) {this .value =value ; }@Override public String toString() {return String.valueOf (value ); } }See Also:
- Overrides:
useEnumNamesin classRestClient.Builder- Returns:
- This object.
-
useJavaBeanIntrospector
Description copied from class:BeanContextable.BuilderUse Java Introspector.Using the built-in Java bean introspector will not pick up fields or non-standard getters/setters.
Most@Beanannotations will be ignored.Example:
// Create a serializer that only uses the built-in java bean introspector for finding properties. WriterSerializerserializer = JsonSerializer .create () .useJavaBeanIntrospector() .build();See Also:
- Overrides:
useJavaBeanIntrospectorin classRestClient.Builder- Returns:
- This object.
-
userTokenHandler
Description copied from class:RestClient.BuilderAssignsUserTokenHandlerinstance.Notes:
- This value can be overridden by the
RestClient.Builder.disableConnectionState()method.
- Overrides:
userTokenHandlerin classRestClient.Builder- 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
Description copied from class:RestClient.BuilderUse system properties when creating and configuring default implementations.- Overrides:
useSystemPropertiesin classRestClient.Builder- Returns:
- This object.
- See Also:
-
useWhitespace
Description copied from class:RestClient.BuilderWriterSerializer 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:
- Overrides:
useWhitespacein classRestClient.Builder- Returns:
- This object.
-
ws
Description copied from class:RestClient.BuilderWriterSerializer 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:
- Overrides:
wsin classRestClient.Builder- Returns:
- This object.
-
xml
Description copied from class:RestClient.BuilderConvenience 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.
RestClient.Builder.sortCollections()) or bean context property setters (e.g.RestClient.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.
RestClient.Builder.strict()) or bean context property setters (e.g.RestClient.Builder.swaps(Class...)) defined on this builder class.
Accept request header will be set to"text/xml" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Content-Type request header will be set to"text/xml" unless overridden viaRestClient.Builder.headers(), or per-request viaRestRequest.header(Header).Can be combined with other marshaller setters such as
RestClient.Builder.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();- Overrides:
xmlin classRestClient.Builder- Returns:
- This object.
- The serializer can be configured using any of the serializer property setters (e.g.
-