@ConfigurableContext(nocache=true) public class RestClient extends BeanContext implements HttpClient, Closeable, RestCallHandler, RestCallInterceptor
Built upon the feature-rich Apache HttpClient library, the Juneau RestClient API adds support for fluent-style REST calls and the ability to perform marshalling of POJOs to and from HTTP parts.
Breaking apart the fluent call, we can see the classes being used:
RestClientBuilder
It additionally provides support for creating remote proxy interfaces using REST as the transport medium.
The classes are closely tied to Apache HttpClient, yet provide lots of additional functionality:
RestClient
HttpClient
, creates RestRequest
objects.
RestRequest
HttpUriRequest
, creates RestResponse
objects.
RestResponse
HttpResponse
, creates RestResponseBody
and RestResponseHeader
objects.
RestResponseBody
HttpEntity
RestResponseHeader
Header
Instances of this class are built using the RestClientBuilder
class which can be constructed using
the RestClient.create()
method as shown above.
Clients are typically created with a root URI so that relative URIs can be used when making requests.
This is done using the RestClientBuilder.rootUri(Object)
method.
The RestClient
class creates RestRequest
objects using the following methods:
The RestRequest
class creates RestResponse
objects using the following methods:
The distinction between the two methods is that complete()
automatically consumes the response body and
run()
does not. Note that you must consume response bodies in order for HTTP connections to be freed up
for reuse! The InputStreams
returned by the RestResponseBody
object are auto-closing once
they are exhausted, so it is often not necessary to explicitly close them.
The following examples show the distinction between the two calls:
By default, JSON support is provided for HTTP request and response bodies. Other languages can be specified using any of the following builder methods:
Clients can also support multiple languages:
When using clients with multiple language support, you must specify the
Languages can also be specified per-request.
The RestClientBuilder
class provides convenience methods for setting common serializer and parser
settings.
Other methods are also provided for specifying the serializers and parsers used for lower-level marshalling support:
HTTP parts (headers, query parameters, form data...) are serialized and parsed using the HttpPartSerializer
and HttpPartParser
APIs. By default, clients are configured to use OpenApiSerializer
and
OpenApiParser
. These can be overridden using the following methods:
Per-client or per-request headers can be specified using the following methods:
Additionally, methods are provided on the client builder and per request for all standard HTTP headers
such as authorization(Object)
.
The supplier methods are particularly useful for header values whose values may change over time (such as
The HttpPartSchema
API allows you to define OpenAPI schemas to POJO data structures on both requests
and responses.
The methods with AddFlag
parameters allow you to control whether new headers get appended, prepended, or
replace existing headers with the same name.
Per-client or per-request query parameters can be specified using the following methods:
Per-client or per-request form-data parameters can be specified using the following methods:
The request body can either be passed in with the client creator method (e.g. post(uri,body)
),
or can be specified via the following methods:
The request body can be any of the following types:
Object
- POJO to be converted to text using the Serializer
defined on the client or request.
Reader
- Raw contents of Reader
will be serialized to remote resource.
InputStream
- Raw contents of InputStream
will be serialized to remote resource.
HttpResource
/BasicHttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request.
HttpEntity
/BasicHttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
NameValuePairSupplier
- Converted to a URL-encoded FORM post.
Supplier
- A supplier of anything on this list.
ClassMeta.toString(Object)
which typically just calls Object.toString()
.
After execution using RestRequest.run()
or RestRequest.complete()
, the following methods can be used
to get the response status:
RestResponse
getStatusLine()
StatusLine
getStatusCode()
getReasonPhrase()
assertStatus()
RestResponseStatusLineAssertion
Equivalent methods with mutable parameters are provided to allow access to status values without breaking fluent call chains.
RestRequest.complete()
instead
of RestRequest.run()
to make sure the response body gets automatically cleaned up. Otherwise you must
consume the response yourself.
The assertion method is provided for quickly asserting status codes in fluent calls.
Response headers are accessed through the following methods:
RestResponse
getHeader(String)
RestResponseHeader
getHeaders(String)
RestResponseHeader
[]getFirstHeader(String)
RestResponseHeader
getLastHeader(String)
RestResponseHeader
getAllHeaders()
RestResponseHeader
[]getStringHeader(String)
containsHeader(String)
Unlike RestResponse.getFirstHeader(String)
and RestResponse.getLastHeader(String)
, the RestResponse.getHeader(String)
method returns an empty RestResponseHeader
object instead of returning
The RestResponseHeader
class extends from the HttpClient Header
class and provides several convenience
methods:
RestResponseHeader
exists()
asString()
asOptionalString()
asStringOrElse(String)
as(Type,Type...)
as(Class<T>)
asOptional(Type,Type...)
asOptional(Class<T>)
asMatcher(Pattern)
Matcher
asMatcher(String)
Matcher
asHeader(Class<T extends BasicHeader> c)
BasicHeader
asStringHeader()
BasicIntegerHeader
asIntegerHeader()
BasicStringHeader
asLongHeader()
BasicLongHeader
asDateHeader()
BasicDateHeader
asCsvArrayHeader()
BasicCsvArrayHeader
asEntityValidatorArrayHeader()
BasicEntityTagArrayHeader
asRangeArrayHeader()
BasicStringRangeArrayHeader
asUriHeader()
BasicUriHeader
The RestResponseHeader.schema(HttpPartSchema)
method allows you to perform parsing of OpenAPI formats for
header parts.
Assertion methods are also provided for fluent-style calls:
RestResponseHeader
assertString()
FluentStringAssertion
assertInteger()
FluentIntegerAssertion
assertLong()
FluentLongAssertion
assertDate()
FluentDateAssertion
Note how in the following example, the fluent assertion returns control to the RestResponse
object after
the assertion has been completed:
The response body is accessed through the following method:
RestResponse
getBody()
RestResponseBody
The RestResponseBody
class extends from the HttpClient HttpEntity
class and provides several convenience
methods:
RestResponseBody
asInputStream()
asReader()
asReader(Charset)
pipeTo(OutputStream)
RestResponse
pipeTo(Writer)
RestResponse
as(Type,Type...)
as(Class<T>)
asFuture(Class<T>)
asFuture(Type,Type...)
asString()
asStringFuture()
asAbbreviatedString(int)
asPojoRest(Class<?>)
PojoRest
asPojoRest()
PojoRest
asMatcher(Pattern)
Matcher
asMatcher(String)
Matcher
The response body can only be consumed once unless it has been cached into memory. In many cases, the body is
automatically cached when using the assertions methods or methods such as RestResponseBody.asString()
.
However, methods that involve reading directly from the input stream cannot be called twice.
In these cases, the RestResponse.cacheBody()
and RestResponseBody.cache()
methods are provided
to cache the response body in memory so that you can perform several operations against it.
Assertion methods are also provided for fluent-style calls:
RestResponseBody
assertString()
FluentStringAssertion
assertObject(Class<?>)
FluentObjectAssertion
assertBytes()
FluentByteArrayAssertion
Object assertions allow you to parse the response body into a POJO and then perform various tests on that resulting POJO.
The RestCallHandler
interface provides the ability to provide custom handling of requests.
RestClientBuilder
RestCallHandler
run(HttpHost,HttpRequest,HttpContext)
Note that there are other ways of accomplishing this such as extending the RestClient
class and overriding
the run(HttpHost,HttpRequest,HttpContext)
method
or by defining your own HttpRequestExecutor
. Using this interface is often simpler though.
The RestCallInterceptor
API provides a quick way of intercepting and manipulating requests and responses beyond
the existing HttpRequestInterceptor
and HttpResponseInterceptor
APIs.
The following methods provide logging of requests and responses:
The following example shows the results of logging all requests that end with
MyBean
This produces the following console output:
=== HTTP Call (outgoing) ====================================================== === REQUEST === POST http://localhost/bean ---request headers--- Accept: application/json+simple ---request entity--- Content-Type: application/json+simple ---request content--- {f:1} === RESPONSE === HTTP/1.1 200 ---response headers--- Content-Type: application/json ---response content--- {f:1} === END =======================================================================",
It should be noted that if you enable request logging detail level DetailLevel.FULL
, response bodies will be cached by default which may introduce
a performance penalty.
Additionally, the following method is also provided for enabling debug mode:
Enabling debug mode has the following effects:
Context.CONTEXT_debug
is enabled.
RESTCLIENT_leakDetection
is enabled.
RestClientBuilder.logToConsole()
is called.
One of the more powerful features of the REST client class is the ability to produce Java interface proxies against arbitrary remote REST resources.
The methods to retrieve remote interfaces are:
RestClient
getRemote(Class<T>)
getRemote(Class<T>,Object)
getRemote(Class<T>,Object,Serializer,Parser)
getRrpcInterface(Class<T>)
getRrpcInterface(Class<T>,Object)
getRrpcInterface(Class<T>,Object,Serializer,Parser)
Two basic types of remote interfaces are provided:
@Remote
-annotated interfaces. These can be defined against arbitrary external REST resources.
Refer to the following documentation on both flavors:
Several methods are provided for customizing the underlying HTTP client and client builder classes:
RestClientBuilder
httpClientBuilder(HttpClientBuilder)
- Set the client builder yourself.
createHttpClientBuilder()
- Override to create the client builder.
createHttpClient()
- Override to create the client.
createConnectionManager()
- Override to create the connection management.
Additionally, all methods on the
Refer to the HTTP Client Builder API
for more information.
The
The RestRequest
and RestResponse
objects can also be extended and integrated by overriding the
createRequest(URI, String, boolean)
and createResponse(RestRequest, HttpResponse, Parser)
methods.
Modifier and Type | Field and Description |
---|---|
static String |
RESTCLIENT_callHandler
Configuration property: REST call handler.
|
static String |
RESTCLIENT_console
Configuration property: Console print stream.
|
static String |
RESTCLIENT_errorCodes
Configuration property: Error codes predicate.
|
static String |
RESTCLIENT_executorService
Configuration property: Executor service.
|
static String |
RESTCLIENT_executorServiceShutdownOnClose
Configuration property: Shut down executor service on close.
|
static String |
RESTCLIENT_formData
Configuration property: Request form-data parameters.
|
static String |
RESTCLIENT_headers
Configuration property: Request headers.
|
static String |
RESTCLIENT_ignoreErrors
Configuration property: Ignore errors.
|
static String |
RESTCLIENT_interceptors
Configuration property: Call interceptors.
|
static String |
RESTCLIENT_interceptors_add
Add to the Call interceptors property.
|
static String |
RESTCLIENT_keepHttpClientOpen
Configuration property: Keep HttpClient open.
|
static String |
RESTCLIENT_leakDetection
Configuration property: Enable leak detection.
|
static String |
RESTCLIENT_logger
Configuration property: Logger.
|
static String |
RESTCLIENT_logRequests
Configuration property: Log requests.
|
static String |
RESTCLIENT_logRequestsLevel
Configuration property: Log requests log level.
|
static String |
RESTCLIENT_logRequestsPredicate
Configuration property: Log requests predicate.
|
static String |
RESTCLIENT_logToConsole
Configuration property: Log to console.
|
static String |
RESTCLIENT_parsers
Configuration property: Parsers.
|
static String |
RESTCLIENT_partParser
Configuration property: Part parser.
|
static String |
RESTCLIENT_partSerializer
Configuration property: Part serializer.
|
static String |
RESTCLIENT_query
Configuration property: Request query parameters.
|
static String |
RESTCLIENT_rootUri
Configuration property: Root URI.
|
static String |
RESTCLIENT_serializers
Configuration property: Serializers.
|
BEAN_annotations, BEAN_beanClassVisibility, BEAN_beanConstructorVisibility, BEAN_beanDictionary, BEAN_beanDictionary_add, BEAN_beanDictionary_remove, BEAN_beanFieldVisibility, BEAN_beanFilters, BEAN_beanFilters_add, BEAN_beanFilters_remove, BEAN_beanMapPutReturnsOldValue, BEAN_beanMethodVisibility, BEAN_beansRequireDefaultConstructor, BEAN_beansRequireSerializable, BEAN_beansRequireSettersForGetters, BEAN_beansRequireSomeProperties, BEAN_bpi, BEAN_bpro, BEAN_bpwo, BEAN_bpx, BEAN_examples, BEAN_excludeProperties, BEAN_fluentSetters, BEAN_ignoreInvocationExceptionsOnGetters, BEAN_ignoreInvocationExceptionsOnSetters, BEAN_ignorePropertiesWithoutSetters, BEAN_ignoreTransientFields, BEAN_ignoreUnknownBeanProperties, BEAN_ignoreUnknownNullBeanProperties, BEAN_implClasses, BEAN_includeProperties, BEAN_notBeanClasses, BEAN_notBeanClasses_add, BEAN_notBeanClasses_remove, BEAN_notBeanPackages, BEAN_notBeanPackages_add, BEAN_notBeanPackages_remove, BEAN_pojoSwaps, BEAN_pojoSwaps_add, BEAN_pojoSwaps_remove, BEAN_propertyNamer, BEAN_sortProperties, BEAN_swaps, BEAN_swaps_add, BEAN_swaps_remove, BEAN_typePropertyName, BEAN_useEnumNames, BEAN_useInterfaceProxies, BEAN_useJavaBeanIntrospector, DEFAULT, DEFAULT_SORTED
CONTEXT_debug, CONTEXT_locale, CONTEXT_mediaType, CONTEXT_timeZone
Modifier | Constructor and Description |
---|---|
protected |
RestClient(PropertyStore ps)
Constructor.
|
Modifier and Type | Method and Description |
---|---|
RestClientBuilder |
builder()
Creates a builder from this context object.
|
RestRequest |
callback(String callString)
Performs a REST call where the entire call is specified in a simple string.
|
void |
close()
Calls
Closeable.close() on the underlying CloseableHttpClient . |
void |
closeQuietly()
Same as
close() , but ignores any exceptions. |
static RestClientBuilder |
create()
Instantiates a new clean-slate
RestClientBuilder object. |
protected RestRequest |
createRequest(URI uri,
String method,
boolean hasBody)
Creates a
RestRequest object from the specified HttpRequest object. |
protected RestResponse |
createResponse(RestRequest request,
HttpResponse httpResponse,
Parser parser)
Creates a
RestResponse object from the specified HttpResponse object. |
RestRequest |
delete(Object uri)
Perform a
|
HttpResponse |
execute(HttpHost target,
HttpRequest request)
Executes HTTP request using the default context.
|
HttpResponse |
execute(HttpHost target,
HttpRequest request,
HttpContext context)
Executes HTTP request using the given context.
|
<T> T |
execute(HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler)
Executes HTTP request to the target using the default context and processes the response using the given response handler.
|
<T> T |
execute(HttpHost target,
HttpRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context)
Executes a request using the default context and processes the response using the given response handler.
|
HttpResponse |
execute(HttpUriRequest request)
Executes HTTP request using the default context.
|
HttpResponse |
execute(HttpUriRequest request,
HttpContext context)
Executes HTTP request using the given context.
|
<T> T |
execute(HttpUriRequest request,
ResponseHandler<? extends T> responseHandler)
Executes HTTP request using the default context and processes the response using the given response handler.
|
<T> T |
execute(HttpUriRequest request,
ResponseHandler<? extends T> responseHandler,
HttpContext context)
Executes HTTP request using the given context and processes the response using the given response handler.
|
protected void |
finalize() |
RestRequest |
formPost(Object uri)
Same as
formPost(Object, Object) but doesn't specify the input yet. |
RestRequest |
formPost(Object uri,
Object body)
Perform a
|
RestRequest |
formPostPairs(Object uri,
Object... parameters)
Perform a
|
RestRequest |
get()
Perform a
|
RestRequest |
get(Object uri)
Perform a
|
ClientConnectionManager |
getConnectionManager()
Deprecated.
Use
HttpClientBuilder . |
HttpParams |
getParams()
Deprecated.
Use
RequestConfig . |
<T> T |
getRemote(Class<T> interfaceClass)
Create a new proxy interface against a 3rd-party REST interface.
|
<T> T |
getRemote(Class<T> interfaceClass,
Object rootUri)
Same as
getRemote(Class) except explicitly specifies the URI of the REST interface. |
<T> T |
getRemote(Class<T> interfaceClass,
Object rootUri,
Serializer serializer,
Parser parser)
Same as
getRemote(Class, Object) but allows you to override the serializer and parser used. |
<T> T |
getRrpcInterface(Class<T> interfaceClass)
Create a new proxy interface against an RRPC-style service.
|
<T> T |
getRrpcInterface(Class<T> interfaceClass,
Object uri)
Same as
getRrpcInterface(Class) except explicitly specifies the URI of the REST interface. |
<T> T |
getRrpcInterface(Class<T> interfaceClass,
Object uri,
Serializer serializer,
Parser parser)
Same as
getRrpcInterface(Class, Object) but allows you to override the serializer and parser used. |
RestRequest |
head(Object uri)
Perform a
|
protected void |
log(Level level,
String msg,
Object... args)
Logs a message.
|
protected void |
log(Level level,
Throwable t,
String msg,
Object... args)
Logs a message.
|
void |
onClose(RestRequest req,
RestResponse res)
Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been set on the request from the client.
|
void |
onConnect(RestRequest req,
RestResponse res)
Interceptor method called immediately after an HTTP response has been received.
|
void |
onInit(RestRequest req)
Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been copied from the client.
|
RestRequest |
options(Object uri)
Perform an
|
RestRequest |
patch(Object uri)
Same as
patch(Object, Object) but don't specify the input yet. |
RestRequest |
patch(Object uri,
Object body)
Perform a
|
RestRequest |
patch(Object uri,
String body,
String contentType)
Perform a
|
RestRequest |
post(Object uri)
Same as
post(Object, Object) but don't specify the input yet. |
RestRequest |
post(Object uri,
Object body)
Perform a
|
RestRequest |
post(Object uri,
String body,
String contentType)
Perform a
|
RestRequest |
put(Object uri)
Same as
put(Object, Object) but don't specify the input yet. |
RestRequest |
put(Object uri,
Object body)
Perform a
|
RestRequest |
put(Object uri,
String body,
String contentType)
Perform a
|
RestRequest |
request(String method,
Object uri)
Perform a generic REST call.
|
RestRequest |
request(String method,
Object uri,
boolean hasBody)
Perform a generic REST call.
|
RestRequest |
request(String method,
Object uri,
Object body)
Perform a generic REST call.
|
HttpResponse |
run(HttpHost target,
HttpRequest request,
HttpContext context)
Entrypoint for executing all requests and returning a response.
|
OMap |
toMap()
Returns the properties defined on this bean context as a simple map for debugging purposes.
|
_class, createBeanSession, createBeanSession, createDefaultBeanSessionArgs, createDefaultSessionArgs, createSession, createSession, createSession, dumpCacheStats, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getAnnotations, getBeanClassVisibility, getBeanConstructorVisibility, getBeanDictionaryClasses, getBeanFieldVisibility, getBeanFilters, getBeanMeta, getBeanMethodVisibility, getBeanRegistry, getBeanToStringSerializer, getBeanTypePropertyName, getBpi, getBpi, getBpro, getBpro, getBpwo, getBpwo, getBpx, getBpx, getClassMeta, getClassMeta, getClassMetaForObject, getDeclaredAnnotations, getDeclaredAnnotations, getExamples, getImplClassConstructor, getImplClasses, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastAnnotation, getLastDeclaredAnnotation, getLastDeclaredAnnotation, getNotBeanClasses, getNotBeanPackagesNames, getNotBeanPackagesPrefixes, getPropertyNamer, getSwaps, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, hasDeclaredAnnotation, hasDeclaredAnnotation, hasSameCache, isBean, isBeanMapPutReturnsOldValue, isBeansRequireDefaultConstructor, isBeansRequireSerializable, isBeansRequireSettersForGetters, isBeansRequireSomeProperties, isFluentSetters, isIgnoreInvocationExceptionsOnGetters, isIgnoreInvocationExceptionsOnSetters, isIgnorePropertiesWithoutSetters, isIgnoreTransientFields, isIgnoreUnknownBeanProperties, isIgnoreUnknownNullBeanProperties, isNotABean, isSortProperties, isUseEnumNames, isUseInterfaceProxies, isUseJavaBeanIntrospector, object, resolveClassMeta, string
equals, getArrayProperty, getArrayProperty, getBooleanProperty, getCdlProperty, getClassArrayProperty, getClassArrayProperty, getClassArrayProperty, getClassListProperty, getClassListProperty, getClassMapProperty, getClassMapProperty, getClassProperty, getClassSetProperty, getClassSetProperty, getDefaultLocale, getDefaultMediaType, getDefaultTimeZone, getInstanceArrayProperty, getInstanceArrayProperty, getInstanceArrayProperty, getInstanceProperty, getInstanceProperty, getInstanceProperty, getIntegerProperty, getListProperty, getListProperty, getLongProperty, getMapProperty, getProperty, getProperty, getPropertyKeys, getPropertyStore, getSetProperty, getSetProperty, getStringProperty, getStringPropertyWithNone, hashCode, identityCode, isDebug, toString
public static final String RESTCLIENT_callHandler
RESTCLIENT_callHandler
RestCallHandler
>RestCallHandler
Allows you to provide a custom handler for making HTTP calls.
public static final String RESTCLIENT_console
RESTCLIENT_console
PrintStream
> | PrintStream
Allows you to redirect the console output to a different print stream.
public static final String RESTCLIENT_errorCodes
RESTCLIENT_errorCodes
Predicate
<Integer
>
x -> x>=400
Defines a predicate to test for error codes.
public static final String RESTCLIENT_executorService
RESTCLIENT_executorService
ExecutorService
>ExecutorService
Defines the executor service to use when calling future methods on the RestRequest
class.
This executor service is used to create Future
objects on the following methods:
RestRequest.runFuture()
RestRequest.completeFuture()
RestResponseBody.asFuture(Class)
(and similar methods)
The default executor service is a single-threaded ThreadPoolExecutor
with a 30 second timeout
and a queue size of 10.
public static final String RESTCLIENT_executorServiceShutdownOnClose
RESTCLIENT_executorServiceShutdownOnClose
Call ExecutorService.shutdown()
when close()
is called.
public static final String RESTCLIENT_formData
RESTCLIENT_formData
NameValuePair
>Query parameters to add to every request.
public static final String RESTCLIENT_headers
RESTCLIENT_headers
Header
| NameValuePair
>RestClientBuilder
header(String,Object)
header(String,Object,HttpPartSerializer,HttpPartSchema)
header(Header)
headers(Object...)
headerPairs(Object...)
accept(Object)
acceptCharset(Object)
acceptEncoding(Object)
acceptLanguage(Object)
authorization(Object)
cacheControl(Object)
clientVersion(Object)
connection(Object)
contentLength(Object)
contentType(Object)
date(Object)
expect(Object)
forwarded(Object)
from(Object)
host(Object)
ifMatch(Object)
ifModifiedSince(Object)
ifNoneMatch(Object)
ifRange(Object)
ifUnmodifiedSince(Object)
maxForwards(Object)
origin(Object)
pragma(Object)
proxyAuthorization(Object)
proxyAuthorization(Object)
referer(Object)
te(Object)
userAgent(Object)
upgrade(Object)
via(Object)
warning(Object)
RestRequest
header(String,Object)
header(EnumSet>AddFlag>,String,Object)
header(Header)
headers(Object...)
headers(EnumSet>AddFlag>,Object...)
headerPairs(Object...)
accept(Object)
acceptCharset(Object)
acceptEncoding(Object)
acceptLanguage(Object)
authorization(Object)
cacheControl(Object)
clientVersion(Object)
connection(Object)
contentLength(Object)
contentType(Object)
date(Object)
expect(Object)
forwarded(Object)
from(Object)
hostHeader(Object)
ifMatch(Object)
ifModifiedSince(Object)
ifNoneMatch(Object)
ifRange(Object)
ifUnmodifiedSince(Object)
maxForwards(Object)
origin(Object)
pragma(Object)
proxyAuthorization(Object)
proxyAuthorization(Object)
referer(Object)
te(Object)
userAgent(Object)
upgrade(Object)
via(Object)
warning(Object)
Headers to add to every request.
public static final String RESTCLIENT_ignoreErrors
RESTCLIENT_ignoreErrors
When enabled, HTTP error response codes (e.g. RestCallException
to
be thrown.
Note that this is equivalent to
public static final String RESTCLIENT_interceptors
RESTCLIENT_interceptors
RestCallInterceptor
> | RestCallInterceptor
>>Adds an interceptor that can be called to hook into specified events in the lifecycle of a single request.
public static final String RESTCLIENT_interceptors_add
public static final String RESTCLIENT_keepHttpClientOpen
RESTCLIENT_keepHttpClientOpen
Don't close this client when the close()
method is called.
public static final String RESTCLIENT_leakDetection
RESTCLIENT_leakDetection
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
Automatically enabled with Context.CONTEXT_debug
.
public static final String RESTCLIENT_logger
RESTCLIENT_logger
Specifies the logger to use for logging.
public static final String RESTCLIENT_logToConsole
RESTCLIENT_logToConsole
When enabled, log messages are sent to the console in addition to the existing logger.
public static final String RESTCLIENT_logRequests
RESTCLIENT_logRequests
DetailLevel.NONE
Causes requests/responses to be logged at the specified log level at the end of the request.
POST http://localhost:10000/testUrl, HTTP/1.1 200 OK
=== 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_logger
setting or logged to the console using the
RESTCLIENT_logToConsole
setting.
public static final String RESTCLIENT_logRequestsLevel
RESTCLIENT_logRequestsLevel
Level.INFO
Used in combination with RESTCLIENT_logRequests
to specify the
level to log request messages to.
public static final String RESTCLIENT_logRequestsPredicate
RESTCLIENT_logRequestsPredicate
Used in combination with RESTCLIENT_logRequests
to specify the
level to log request messages to.
public static final String RESTCLIENT_parsers
RESTCLIENT_parsers
Associates the specified Parsers
with the HTTP client.
The parsers are used to parse the HTTP response body into a POJO.
The parser that best matches the
If no
public static final String RESTCLIENT_partParser
RESTCLIENT_partParser
HttpPartParser
>HttpPartParser
OpenApiParser
;
The parser to use for parsing POJOs from form data, query parameters, headers, and path variables.
The default part parser is OpenApiParser
which allows for schema-driven marshalling.
public static final String RESTCLIENT_partSerializer
RESTCLIENT_partSerializer
HttpPartSerializer
>HttpPartSerializer
OpenApiSerializer
;
The serializer to use for serializing POJOs in form data, query parameters, headers, and path variables.
The default part serializer is OpenApiSerializer
which allows for schema-driven marshalling.
public static final String RESTCLIENT_query
RESTCLIENT_query
NameValuePair
>Query parameters to add to every request.
public static final String RESTCLIENT_rootUri
RESTCLIENT_rootUri
When set, relative URI strings passed in through the various rest call methods (e.g. get(Object)
will be prefixed with the specified root.
This root URI is ignored on those methods if you pass in a URL
, URI
, or an absolute URI string.
public static final String RESTCLIENT_serializers
RESTCLIENT_serializers
Serializer
>Serializer
Associates the specified Serializers
with the HTTP client.
The serializer is used to serialize POJOs into the HTTP request body.
The serializer that best matches the
If no
protected RestClient(PropertyStore ps)
ps
- The property store containing the unmodifiable configuration for this client.public static RestClientBuilder create()
RestClientBuilder
object.RestClientBuilder
object.public RestClientBuilder builder()
Context
Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
builder
in class BeanContext
public void close() throws IOException
Closeable.close()
on the underlying CloseableHttpClient
.
It's good practice to call this method after the client is no longer used.
close
in interface Closeable
close
in interface AutoCloseable
IOException
- Thrown by underlying stream.public void closeQuietly()
close()
, but ignores any exceptions.public HttpResponse run(HttpHost target, HttpRequest request, HttpContext context) throws ClientProtocolException, IOException
Subclasses can override this method to provide specialized handling.
The behavior of this method can also be modified by specifying a different RestCallHandler
.
run
in interface RestCallHandler
target
- The target host for the request.
request
- The request to execute.context
- The context to use for the execution, or IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public RestRequest get(Object uri) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest get() throws RestCallException
RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest put(Object uri, Object body) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request.
Can be of the following types:
Reader
- Raw contents of Reader
will be serialized to remote resource.
InputStream
- Raw contents of InputStream
will be serialized to remote resource.
Object
- POJO to be converted to text using the Serializer
registered with the
RestClient
.
HttpEntity
/ HttpResource
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
NameValuePairSupplier
- Converted to a URL-encoded FORM post.
Supplier
- A supplier of anything on this list.
RestRequest
object that can be further tailored before executing the request
and getting the response as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest put(Object uri, String body, String contentType) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request bypassing the serializer.contentType
- The content type of the request.RestRequest
object that can be further tailored before executing the request
and getting the response as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest put(Object uri) throws RestCallException
put(Object, Object)
but don't specify the input yet.
You must call either RestRequest.body(Object)
or RestRequest.formData(String, Object)
to set the contents on the result object.
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- REST call failed.public RestRequest post(Object uri, Object body) throws RestCallException
formPost(Object, Object)
for uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request.
Can be of the following types:
Reader
- Raw contents of Reader
will be serialized to remote resource.
InputStream
- Raw contents of InputStream
will be serialized to remote resource.
Object
- POJO to be converted to text using the Serializer
registered with the
RestClient
.
HttpEntity
/ HttpResource
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
NameValuePairSupplier
- Converted to a URL-encoded FORM post.
Supplier
- A supplier of anything on this list.
RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest post(Object uri, String body, String contentType) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request bypassing the serializer.contentType
- The content type of the request.RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest post(Object uri) throws RestCallException
post(Object, Object)
but don't specify the input yet.
You must call either RestRequest.body(Object)
or RestRequest.formData(String, Object)
to set the
contents on the result object.
formPost(Object, Object)
for uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- REST call failed.public RestRequest delete(Object uri) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest options(Object uri) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest head(Object uri) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest formPost(Object uri, Object body) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request.
NameValuePair
- URL-encoded as a single name-value pair.
NameValuePair
array - URL-encoded as name value pairs.
NameValuePairSupplier
- URL-encoded as name value pairs.
Reader
/InputStream
- Streamed directly and HttpResource
/BasicHttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request.
HttpEntity
/BasicHttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
Object
- Converted to a SerializedHttpEntity
using UrlEncodingSerializer
to serialize.
Supplier
- A supplier of anything on this list.
RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest formPost(Object uri) throws RestCallException
formPost(Object, Object)
but doesn't specify the input yet.uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest formPostPairs(Object uri, Object... parameters) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to parameters
- The parameters of the form post.
BasicNameValuePair
objects.RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest patch(Object uri, Object body) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request.
Can be of the following types:
Reader
- Raw contents of Reader
will be serialized to remote resource.
InputStream
- Raw contents of InputStream
will be serialized to remote resource.
HttpResource
/BasicHttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request.
HttpEntity
/BasicHttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
Object
- POJO to be converted to text using the Serializer
registered with the
RestClient
.
NameValuePairSupplier
- Converted to a URL-encoded FORM post.
Supplier
- A supplier of anything on this list.
RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest patch(Object uri, String body, String contentType) throws RestCallException
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The object to serialize and transmit to the URI as the body of the request bypassing the serializer.contentType
- The content type of the request.RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest patch(Object uri) throws RestCallException
patch(Object, Object)
but don't specify the input yet.
You must call RestRequest.body(Object)
to set the contents on the result object.
uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- REST call failed.public RestRequest callback(String callString) throws RestCallException
This method is useful for performing callbacks when the target of a callback is passed in on an initial request, for example to signal when a long-running process has completed.
The call string can be any of the following formats:
The payload will always be sent using a simple StringEntity
.
callString
- The call string.RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- REST call failed.public RestRequest request(String method, Object uri, Object body) throws RestCallException
method
- The HTTP method.uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to body
- The HTTP body content.
Can be of the following types:
Reader
- Raw contents of Reader
will be serialized to remote resource.
InputStream
- Raw contents of InputStream
will be serialized to remote resource.
HttpResource
/BasicHttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request.
HttpEntity
/BasicHttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.
Object
- POJO to be converted to text using the Serializer
registered with the
RestClient
.
NameValuePairSupplier
- Converted to a URL-encoded FORM post.
Supplier
- A supplier of anything on this list.
RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest request(String method, Object uri) throws RestCallException
method
- The HTTP method.uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.public RestRequest request(String method, Object uri, boolean hasBody) throws RestCallException
Typically you're going to use request(String, Object)
or request(String, Object, Object)
,
but this method is provided to allow you to perform non-standard HTTP methods (e.g. HTTP FOO).
method
- The method name (e.g. uri
- The URI of the remote REST resource.
URIBuilder
URI
URL
String
Object
- Converted to hasBody
- Boolean flag indicating if the specified request has content associated with it.RestRequest
object that can be further tailored before executing the request and getting the response
as a parsed object.RestCallException
- If any authentication errors occurred.protected RestRequest createRequest(URI uri, String method, boolean hasBody) throws RestCallException
RestRequest
object from the specified HttpRequest
object.
Subclasses can override this method to provide their own specialized RestRequest
objects.
uri
- The target.method
- The HTTP method (uppercase).hasBody
- Whether this method has a request entity.RestRequest
object.RestCallException
- If an exception or non-200 response code occurred during the connection attempt.protected RestResponse createResponse(RestRequest request, HttpResponse httpResponse, Parser parser) throws RestCallException
RestResponse
object from the specified HttpResponse
object.
Subclasses can override this method to provide their own specialized RestResponse
objects.
request
- The request creating this response.httpResponse
- The response object to wrap.parser
- The parser to use to parse the response.RestResponse
object.RestCallException
- If an exception or non-200 response code occurred during the connection attempt.public <T> T getRemote(Class<T> interfaceClass)
The URI to the REST interface is based on the following values:
@Remote(path)
annotation on the interface (rootUri
on the client (The URI calculation is as follows:
If the information is not available to resolve to an absolute URI, a RemoteMetadataException
is thrown.
interfaceClass
- The interface to create a proxy for.RemoteMetadataException
- If the REST URI cannot be determined based on the information given.public <T> T getRemote(Class<T> interfaceClass, Object rootUri)
getRemote(Class)
except explicitly specifies the URI of the REST interface.
interfaceClass
- The interface to create a proxy for.rootUri
- The URI of the REST interface.public <T> T getRemote(Class<T> interfaceClass, Object rootUri, Serializer serializer, Parser parser)
getRemote(Class, Object)
but allows you to override the serializer and parser used.
interfaceClass
- The interface to create a proxy for.rootUri
- The URI of the REST interface.serializer
- The serializer used to serialize POJOs to the body of the HTTP request.parser
- The parser used to parse POJOs from the body of the HTTP response.public <T> T getRrpcInterface(Class<T> interfaceClass)
Remote interfaces are interfaces exposed on the server side using either the
The URI to the REST interface is based on the following values:
@Remote(path)
annotation on the interface (rootUri
on the client (The URI calculation is as follows:
If the information is not available to resolve to an absolute URI, a RemoteMetadataException
is thrown.
interfaceClass
- The interface to create a proxy for.RemoteMetadataException
- If the REST URI cannot be determined based on the information given.public <T> T getRrpcInterface(Class<T> interfaceClass, Object uri)
getRrpcInterface(Class)
except explicitly specifies the URI of the REST interface.
interfaceClass
- The interface to create a proxy for.uri
- The URI of the REST interface.public <T> T getRrpcInterface(Class<T> interfaceClass, Object uri, Serializer serializer, Parser parser)
getRrpcInterface(Class, Object)
but allows you to override the serializer and parser used.
interfaceClass
- The interface to create a proxy for.uri
- The URI of the REST interface.serializer
- The serializer used to serialize POJOs to the body of the HTTP request.parser
- The parser used to parse POJOs from the body of the HTTP response.protected void log(Level level, Throwable t, String msg, Object... args)
level
- The log level.t
- Thrown exception. Can be msg
- The message.args
- Optional message arguments.protected void log(Level level, String msg, Object... args)
level
- The log level.msg
- The message with MessageFormat
-style arguments.args
- The arguments.public void onInit(RestRequest req) throws RestCallException
Subclasses can override this method to intercept the request and perform special modifications.
onInit
in interface RestCallInterceptor
req
- The HTTP request.RestCallException
- If any of the interceptors threw an exception.public void onConnect(RestRequest req, RestResponse res) throws RestCallException
Subclasses can override this method to intercept the response and perform special modifications.
onConnect
in interface RestCallInterceptor
req
- The HTTP request.res
- The HTTP response.RestCallException
- If any of the interceptors threw an exception.public void onClose(RestRequest req, RestResponse res) throws RestCallException
Subclasses can override this method to handle any cleanup operations.
onClose
in interface RestCallInterceptor
req
- The HTTP request.res
- The HTTP response.RestCallException
- If any of the interceptors threw an exception.@Deprecated public HttpParams getParams()
RequestConfig
.getParams
in interface HttpClient
@Deprecated public ClientConnectionManager getConnectionManager()
HttpClientBuilder
.getConnectionManager
in interface HttpClient
public HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException
HttpClient
class.
execute
in interface HttpClient
request
- The request to execute.IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException
HttpClient
class.
execute
in interface HttpClient
request
- The request to execute.context
- The context to use for the execution, or IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException
HttpClient
class.
execute
in interface HttpClient
target
- The target host for the request.
request
- The request to execute.IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException
HttpClient
class.
run(HttpHost,HttpRequest,HttpContext)
method has been provided as a wrapper around this method.
Subclasses can override these methods for handling requests with and without bodies separately.
RestCallHandler
interface can also be implemented to intercept this method.
execute
in interface HttpClient
target
- The target host for the request.
request
- The request to execute.context
- The context to use for the execution, or IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException
The content entity associated with the response is fully consumed and the underlying connection is released back
to the connection manager automatically in all cases relieving individual ResponseHandlers
from having to manage resource deallocation internally.
HttpClient
class.
execute
in interface HttpClient
request
- The request to execute.responseHandler
- The response handler.IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException
The content entity associated with the response is fully consumed and the underlying connection is released back
to the connection manager automatically in all cases relieving individual ResponseHandlers
from having to manage resource deallocation internally.
HttpClient
class.
execute
in interface HttpClient
request
- The request to execute.responseHandler
- The response handler.context
- The context to use for the execution, or IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException
The content entity associated with the response is fully consumed and the underlying connection is released back
to the connection manager automatically in all cases relieving individual ResponseHandlers
from having to manage resource deallocation internally.
HttpClient
class.
execute
in interface HttpClient
target
- The target host for the request.
request
- The request to execute.responseHandler
- The response handler.IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException
The content entity associated with the response is fully consumed and the underlying connection is released back
to the connection manager automatically in all cases relieving individual ResponseHandlers
from having to manage resource deallocation internally.
HttpClient
class.
execute
in interface HttpClient
target
- The target host for the request.
request
- The request to execute.responseHandler
- The response handler.context
- The context to use for the execution, or IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.public OMap toMap()
Context
toMap
in class BeanContext
Copyright © 2016–2020 The Apache Software Foundation. All rights reserved.