Class RestClient
- All Implemented Interfaces:
Closeable
,AutoCloseable
,HttpClient
,AnnotationProvider
- Direct Known Subclasses:
MockRestClient
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.
Example:
Breaking apart the fluent call, we can see the classes being used:
RestClient.Builder
It additionally provides support for creating remote proxy interfaces using REST as the transport medium.
Example:
The classes are closely tied to Apache HttpClient, yet provide lots of additional functionality:
RestClient
extends HttpClient
, createsRestRequest
objects.RestRequest
extends HttpUriRequest
, createsRestResponse
objects.RestResponse
createsResponseContent
andResponseHeader
objects.ResponseContent
extends HttpEntity
ResponseHeader
extends Header
Instances of this class are built using the RestClient.Builder
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 RestClient.Builder.rootUrl(Object)
method.
Example:
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 ResponseContent
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:
POJO Marshalling
By default, JSON support is provided for HTTP request and response bodies. Other languages can be specified using any of the following builder methods:
Example:
Clients can also support multiple languages:
Example:
When using clients with multiple language support, you must specify the
Languages can also be specified per-request.
The RestClient.Builder
class provides convenience methods for setting common serializer and parser
settings.
Example:
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:
Request Headers
Per-client or per-request headers can be specified using the following methods:
The supplier methods are particularly useful for header values whose values may change over time (such as
Example:
The HttpPartSchema
API allows you to define OpenAPI schemas to POJO data structures on both requests
and responses.
Example:
The methods with ListOperation
parameters allow you to control whether new headers get appended, prepended, or
replace existing headers with the same name.
Notes:
- Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in
Header orNameValuePair objects use the values returned by that bean directly.
Request Query Parameters
Per-client or per-request query parameters can be specified using the following methods:
Example:
Notes:
- Like header values, dynamic values and OpenAPI schemas are supported.
- Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in
NameValuePair objects use the values returned by that bean directly.
Request Form Data
Per-client or per-request form-data parameters can be specified using the following methods:
Notes:
- Like header values, dynamic values and OpenAPI schemas are supported.
- Methods that pass in POJOs convert values to strings using the part serializers. Methods that pass in
NameValuePair objects use the values returned by that bean directly.
Request Body
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 theSerializer
defined on the client or request. -
Reader
- Raw contents ofReader
will be serialized to remote resource. -
InputStream
- Raw contents ofInputStream
will be serialized to remote resource. -
HttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. -
HttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient. -
PartList
- Converted to a URL-encoded FORM post. -
Supplier
- A supplier of anything on this list.
Notes:
- If the serializer on the client or request is explicitly set to
null , POJOs will be converted to strings using the registered part serializer as content type"text/plain . If the part serializer is alsonull , POJOs will be converted to strings usingClassMeta.toString(Object)
which typically just callsObject.toString()
.
Response Status
After execution using RestRequest.run()
or RestRequest.complete()
, the following methods can be used
to get the response status:
RestResponse
getStatusLine()
returns StatusLine
getStatusCode()
returns int getReasonPhrase()
returns StringassertStatus()
returns FluentResponseStatusLineAssertion
Example:
Equivalent methods with mutable parameters are provided to allow access to status values without breaking fluent call chains.
Example:
Notes:
- If you are only interested in the response status and not the response body, be sure to use
RestRequest.complete()
instead ofRestRequest.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.
Example:
Response Headers
Response headers are accessed through the following methods:
RestResponse
getHeaders(String)
returns ResponseHeader
[]getFirstHeader(String)
returns ResponseHeader
getLastHeader(String)
returns ResponseHeader
getAllHeaders()
returns ResponseHeader
[]getStringHeader(String)
returns StringcontainsHeader(String)
returns boolean
The RestResponse.getFirstHeader(String)
and RestResponse.getLastHeader(String)
methods return an empty ResponseHeader
object instead of
Example:
The ResponseHeader
class extends from the HttpClient Header
class and provides several convenience
methods:
ResponseHeader
isPresent()
returns boolean asString()
returns Stringas(Type,Type...)
returns Tas(Class<T>)
returns TasMatcher(Pattern)
returns Matcher
asMatcher(String)
returns Matcher
asHeader(Class<T
extends BasicHeader> c)returns BasicHeader
asStringHeader()
returns BasicStringHeader
asIntegerHeader()
returns BasicIntegerHeader
asLongHeader()
returns BasicLongHeader
asDateHeader()
returns BasicDateHeader
asCsvHeader()
returns BasicCsvHeader
asEntityTagsHeader()
returns BasicEntityTagsHeader
asStringRangesHeader()
returns BasicStringRangesHeader
asUriHeader()
returns BasicUriHeader
The ResponseHeader.schema(HttpPartSchema)
method allows you to perform parsing of OpenAPI formats for
header parts.
Example:
Assertion methods are also provided for fluent-style calls:
Note how in the following example, the fluent assertion returns control to the RestResponse
object after
the assertion has been completed:
Example:
Response Body
The response body is accessed through the following method:
RestResponse
getContent()
returns ResponseContent
The ResponseContent
class extends from the HttpClient HttpEntity
class and provides several convenience
methods:
ResponseContent
asInputStream()
returns InputStreamasReader()
returns ReaderasReader(Charset)
returns ReaderpipeTo(OutputStream)
returns RestResponse
pipeTo(Writer)
returns RestResponse
as(Type,Type...)
returns Tas(Class<T>)
returns TasFuture(Class<T>)
returns Future<T>asFuture(Type,Type...)
returns Future<T>asString()
returns StringasStringFuture()
returns Future<String>asAbbreviatedString(int)
returns StringasObjectRest(Class<?>)
returns ObjectRest
asObjectRest()
returns ObjectRest
asMatcher(Pattern)
returns Matcher
asMatcher(String)
returns Matcher
Examples:
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 ResponseContent.asString()
.
However, methods that involve reading directly from the input stream cannot be called twice.
In these cases, the RestResponse.cacheContent()
and ResponseContent.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:
Example:
Object assertions allow you to parse the response body into a POJO and then perform various tests on that resulting POJO.
Example:
Custom Call Handlers
The RestCallHandler
interface provides the ability to provide custom handling of requests.
RestClient.Builder
RestCallHandler
run(HttpHost,HttpRequest,HttpContext)
returns HttpResponse
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.
Interceptors
The RestCallInterceptor
API provides a quick way of intercepting and manipulating requests and responses beyond
the existing HttpRequestInterceptor
and HttpResponseInterceptor
APIs.
Logging / Debugging
The following methods provide logging of requests and responses:
The following example shows the results of logging all requests that end with
Examples:
MyBean
This produces the following console output:
=== HTTP Call (outgoing) ====================================================== === REQUEST === POST http://localhost/bean ---request headers--- Accept: application/json5 ---request entity--- Content-Type: application/json5 ---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.Builder.debug()
is enabled.RestClient.Builder.detectLeaks()
is enabled.RestClient.Builder.logToConsole()
is called.
REST Proxies
One of the more powerful features of the REST client class is the ability to produce Java interface proxies against arbitrary remote REST resources.
Example:
The methods to retrieve remote interfaces are:
RestClient
getRemote(Class<T>)
returns TgetRemote(Class<T>,Object)
returns TgetRemote(Class<T>,Object,Serializer,Parser)
returns TgetRrpcInterface(Class<T>)
returns TgetRrpcInterface(Class<T>,Object)
returns TgetRrpcInterface(Class<T>,Object,Serializer,Parser)
returns T
Two basic types of remote interfaces are provided:
@Remote
-annotated interfaces. These can be defined against arbitrary external REST resources.- RPC-over-REST interfaces. These are Java interfaces that allow you to make method calls on server-side POJOs.
Refer to the following documentation on both flavors:
Customizing Apache HttpClient
Several methods are provided for customizing the underlying HTTP client and client builder classes:
RestClient.Builder
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
Example:
Refer to the HTTP Client Builder API
for more information.
Extending RestClient
The
Example:
The RestRequest
and RestResponse
objects can also be extended and integrated by overriding the
createRequest(URI,String,boolean)
and createResponse(RestRequest,HttpResponse,Parser)
methods.
Notes:
- This class is thread safe and reusable.
See Also:
-
Nested Class Summary
-
Field Summary
Fields inherited from class org.apache.juneau.Context
CONTEXT_APPLY_FILTER
Fields inherited from interface org.apache.juneau.AnnotationProvider
DEFAULT, DISABLE_ANNOTATION_CACHING
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionPerforms a REST call where the entire call is specified in a simple string.void
close()
CallsCloseable.close()
on the underlyingCloseableHttpClient
.void
Same asclose()
, but ignores any exceptions.copy()
Creates a builder from this context object.static RestClient.Builder
create()
Instantiates a new clean-slateRestClient.Builder
object.Creates a mutable copy of the form data defined on this client.Creates a mutable copy of the header data defined on this client.Creates a mutable copy of the path data defined on this client.Creates a mutable copy of the query data defined on this client.protected RestRequest
createRequest
(URI uri, String method, boolean hasBody) Creates aRestRequest
object from the specifiedHttpRequest
object.protected RestResponse
createResponse
(RestRequest request, HttpResponse httpResponse, Parser parser) Creates aRestResponse
object from the specifiedHttpResponse
object.Perform aDELETE request against the specified URI.execute
(HttpUriRequest request) Executes HTTP request using the default 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.execute
(HttpUriRequest request, HttpContext context) Executes HTTP request using the given context.execute
(HttpHost target, HttpRequest request) Executes HTTP request using the default 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.execute
(HttpHost target, HttpRequest request, HttpContext context) Executes HTTP request using the given context.protected void
finalize()
Same asformPost(Object, Object)
but doesn't specify the input yet.Perform aPOST request with a content type ofapplication/x-www-form-urlencoded against the specified URI.formPostPairs
(Object uri, String... parameters) Perform aPOST request with a content type ofapplication/x-www-form-urlencoded against the specified URI.get()
Perform aGET request against the root URI.Perform aGET request against the specified URI.Deprecated.Returns the connection manager if one was specified in the client builder.Deprecated.UseRequestConfig
.protected HttpPartParser
Returns the part parser associated with this client.protected HttpPartParser
getPartParser
(Class<? extends HttpPartParser> c) Returns the part parser instance of the specified type.protected HttpPartSerializer
Returns the part serializer associated with this client.protected HttpPartSerializer
getPartSerializer
(Class<? extends HttpPartSerializer> c) Returns the part serializer instance of the specified type.<T> T
Create a new proxy interface against a 3rd-party REST interface.<T> T
Same asgetRemote(Class)
except explicitly specifies the URI of the REST interface.<T> T
getRemote
(Class<T> interfaceClass, Object rootUrl, Serializer serializer, Parser parser) Same asgetRemote(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 asgetRrpcInterface(Class)
except explicitly specifies the URI of the REST interface.<T> T
getRrpcInterface
(Class<T> interfaceClass, Object uri, Serializer serializer, Parser parser) Same asgetRrpcInterface(Class, Object)
but allows you to override the serializer and parser used.Perform aHEAD request against the specified URI.protected void
init()
Gets called add the end of the constructor call to perform any post-initialization.protected void
init
(RestClient.Builder builder) Perform optional initialization on builder before it is used.protected boolean
Returnstrue if empty request form-data parameter values should be ignored.protected boolean
Returnstrue if empty request header values should be ignored.protected boolean
Returnstrue if empty request query parameter values should be ignored.protected void
Logs a message.protected void
Logs a message.protected void
onCallClose
(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.protected void
onCallConnect
(RestRequest req, RestResponse res) Interceptor method called immediately after an HTTP response has been received.protected void
onCallInit
(RestRequest req) Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been copied from the client.Perform anOPTIONS request against the specified URI.Same aspatch(Object, Object)
but don't specify the input yet.Perform aPATCH request against the specified URI.patch
(Object uri, String body, ContentType contentType) Perform aPATCH request against the specified URI as a plain text body bypassing the serializer.Same aspost(Object, Object)
but don't specify the input yet.Perform aPOST request against the specified URI.post
(Object uri, String body, ContentType contentType) Perform aPOST request against the specified URI as a plain text body bypassing the serializer.protected JsonMap
Returns the properties on this bean as a map for debugging.Same asput(Object, Object)
but don't specify the input yet.Perform aPUT request against the specified URI.put
(Object uri, String body, ContentType contentType) Perform aPUT request against the specified URI using a plain text body bypassing the serializer.Perform a generic REST call.Perform a generic REST call.Perform a generic REST call.protected RestRequest
request
(RestOperation op) Perform an arbitrary request against the specified URI.protected HttpResponse
run
(HttpHost target, HttpRequest request, HttpContext context) Entrypoint for executing all requests and returning a response.Methods inherited from class org.apache.juneau.BeanContextable
getBeanContext
Methods inherited from class org.apache.juneau.Context
createBuilder, createSession, firstAnnotation, firstAnnotation, firstAnnotation, firstAnnotation, firstDeclaredAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachDeclaredAnnotation, getSession, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, init, isDebug, lastAnnotation, lastAnnotation, lastAnnotation, lastAnnotation, lastDeclaredAnnotation, toString
-
Constructor Details
-
RestClient
Constructor.- Parameters:
builder
- The builder for this client.
-
-
Method Details
-
create
Instantiates a new clean-slateRestClient.Builder
object.- Returns:
- A new
RestClient.Builder
object.
-
copy
Description copied from class:Context
Creates a builder from this context object.Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
-
init
Perform optional initialization on builder before it is used.Default behavior is a no-op.
- Parameters:
builder
- The builder to initialize.
-
init
Gets called add the end of the constructor call to perform any post-initialization. -
close
CallsCloseable.close()
on the underlyingCloseableHttpClient
.It's good practice to call this method after the client is no longer used.
- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
- Throws:
IOException
- Thrown by underlying stream.
-
closeQuietly
Same asclose()
, but ignores any exceptions. -
run
protected HttpResponse run(HttpHost target, HttpRequest request, HttpContext context) throws ClientProtocolException, IOException Entrypoint for executing all requests and returning a response.Subclasses can override this method to provide specialized handling.
The behavior of this method can also be modified by specifying a different
RestCallHandler
.See Also:
- Parameters:
target
- The target host for the request.
Implementations may acceptnull if they can still determine a route, for example to a default target or by inspecting the request.request
- The request to execute.context
- The context to use for the execution, ornull to use the default context.- Returns:
- The response to the request.
This is always a final response, never an intermediate response with an 1xx status code.
Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. - Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
-
get
Perform aGET request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
get
Perform aGET request against the root URI.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
put
Perform aPUT request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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 ofReader
will be serialized to remote resource. -
InputStream
- Raw contents ofInputStream
will be serialized to remote resource. -
Object
- POJO to be converted to text using theSerializer
registered with theRestClient
. -
HttpEntity
/HttpResource
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient. -
PartList
- Converted to a URL-encoded FORM post. -
Supplier
- A supplier of anything on this list.
-
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
put
Perform aPUT request against the specified URI using a plain text body bypassing the serializer.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
put
Same asput(Object, Object)
but don't specify the input yet.You must call either
RestRequest.content(Object)
orRestRequest.formData(String, Object)
to set the contents on the result object.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- REST call failed.
-
post
Perform aPOST request against the specified URI.Notes:
- Use
formPost(Object, Object)
forapplication/x-www-form-urlencoded form posts.
- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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 ofReader
will be serialized to remote resource. -
InputStream
- Raw contents ofInputStream
will be serialized to remote resource. -
Object
- POJO to be converted to text using theSerializer
registered with theRestClient
. -
HttpEntity
/HttpResource
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient. -
PartList
- Converted to a URL-encoded FORM post. -
Supplier
- A supplier of anything on this list.
-
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
- Use
-
post
Perform aPOST request against the specified URI as a plain text body bypassing the serializer.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
post
Same aspost(Object, Object)
but don't specify the input yet.You must call either
RestRequest.content(Object)
orRestRequest.formData(String, Object)
to set the contents on the result object.Notes:
- Use
formPost(Object, Object)
forapplication/x-www-form-urlencoded form posts.
- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- REST call failed.
- Use
-
delete
Perform aDELETE request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
options
Perform anOPTIONS request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
head
Perform aHEAD request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
formPost
Perform aPOST request with a content type ofapplication/x-www-form-urlencoded against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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.PartList
- URL-encoded as name value pairs.Reader
/InputStream
- Streamed directly andContent-Type set to"application/x-www-form-urlencoded" HttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request.HttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient.Object
- Converted to aSerializedEntity
usingUrlEncodingSerializer
to serialize.Supplier
- A supplier of anything on this list.
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
formPost
Same asformPost(Object, Object)
but doesn't specify the input yet.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
formPostPairs
Perform aPOST request with a content type ofapplication/x-www-form-urlencoded against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
parameters
- The parameters of the form post.
The parameters represent name/value pairs and must be an even number of arguments.
Parameters are converted toBasicPart
objects.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
patch
Perform aPATCH request against the specified URI.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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 ofReader
will be serialized to remote resource. -
InputStream
- Raw contents ofInputStream
will be serialized to remote resource. -
HttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. -
HttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient. -
Object
- POJO to be converted to text using theSerializer
registered with theRestClient
. -
PartList
- Converted to a URL-encoded FORM post. -
Supplier
- A supplier of anything on this list.
-
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
patch
Perform aPATCH request against the specified URI as a plain text body bypassing the serializer.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
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.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
patch
Same aspatch(Object, Object)
but don't specify the input yet.You must call
RestRequest.content(Object)
to set the contents on the result object.- Parameters:
uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- REST call failed.
-
callback
Performs a REST call where the entire call is specified in a simple string.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:
-
"[method] [uri]" - e.g."GET http://localhost/callback" -
"[method] [uri] [payload]" - e.g."POST http://localhost/callback some text payload" -
"[method] [headers] [uri] [payload]" - e.g."POST {'Content-Type':'text/json'} http://localhost/callback {'some':'json'}"
The payload will always be sent using a simple
StringEntity
.- Parameters:
callString
- The call string.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- REST call failed.
-
-
request
Perform a generic REST call.- Parameters:
method
- The HTTP method.uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
body
- The HTTP body content. Can be of the following types:-
Reader
- Raw contents ofReader
will be serialized to remote resource. -
InputStream
- Raw contents ofInputStream
will be serialized to remote resource. -
HttpResource
- Raw contents will be serialized to remote resource. Additional headers and media type will be set on request. -
HttpEntity
- Bypass Juneau serialization and pass HttpEntity directly to HttpClient. -
Object
- POJO to be converted to text using theSerializer
registered with theRestClient
. -
PartList
- Converted to a URL-encoded FORM post. -
Supplier
- A supplier of anything on this list.
-
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
request
Perform a generic REST call.- Parameters:
method
- The HTTP method.uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
request
Perform a generic REST call.Typically you're going to use
request(String, Object)
orrequest(String, Object, Object)
, but this method is provided to allow you to perform non-standard HTTP methods (e.g. HTTP FOO).- Parameters:
method
- The method name (e.g."GET" ,"OPTIONS" ).uri
- The URI of the remote REST resource.
Can be any of the following types:URIBuilder
URI
URL
String
Object
- Converted toString usingtoString()
hasBody
- Boolean flag indicating if the specified request has content associated with it.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
request
Perform an arbitrary request against the specified URI.All requests feed through this method so it can be used to intercept request creations and make modifications (such as add headers).
- Parameters:
op
- The operation that identifies the HTTP method, URL, and optional payload.- Returns:
- A
RestRequest
object that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException
- If any authentication errors occurred.
-
createRequest
protected RestRequest createRequest(URI uri, String method, boolean hasBody) throws RestCallException Creates aRestRequest
object from the specifiedHttpRequest
object.Subclasses can override this method to provide their own specialized
RestRequest
objects.- Parameters:
uri
- The target.method
- The HTTP method (uppercase).hasBody
- Whether this method has a request entity.- Returns:
- A new
RestRequest
object. - Throws:
RestCallException
- If an exception or non-200 response code occurred during the connection attempt.
-
createResponse
protected RestResponse createResponse(RestRequest request, HttpResponse httpResponse, Parser parser) throws RestCallException Creates aRestResponse
object from the specifiedHttpResponse
object.Subclasses can override this method to provide their own specialized
RestResponse
objects.- Parameters:
request
- The request creating this response.httpResponse
- The response object to wrap.parser
- The parser to use to parse the response.- Returns:
- A new
RestResponse
object. - Throws:
RestCallException
- If an exception or non-200 response code occurred during the connection attempt.
-
getRemote
Create a new proxy interface against a 3rd-party REST interface.The URI to the REST interface is based on the following values:
- The
@Remote(path)
annotation on the interface (remote-path ). - The
rootUrl
on the client (root-url ). - The fully-qualified class name of the interface (
class-name ).
The URI calculation is as follows:
remote-path - If remote path is absolute.root-uri/remote-path - If remote path is relative and root-uri has been specified.root-uri/class-name - If remote path is not specified.
If the information is not available to resolve to an absolute URI, a
RemoteMetadataException
is thrown.Examples:
package org.apache.foo;@RemoteResource (path="http://hostname/resturi/myinterface1" )public interface MyInterface1 { ... }@RemoteResource (path="/myinterface2" )public interface MyInterface2 { ... }public interface MyInterface3 { ... }// Resolves to "http://localhost/resturi/myinterface1" MyInterface1interface1 = RestClient .create () .build() .getRemote(MyInterface1.class );// Resolves to "http://hostname/resturi/myinterface2" MyInterface2interface2 = RestClient .create () .rootUrl("http://hostname/resturi" ) .build() .getRemote(MyInterface2.class );// Resolves to "http://hostname/resturi/org.apache.foo.MyInterface3" MyInterface3interface3 = RestClient .create () .rootUrl("http://hostname/resturi" ) .build() .getRemote(MyInterface3.class );Notes:
- If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying pooling client connection manager.
See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
interfaceClass
- The interface to create a proxy for.- Returns:
- The new proxy interface.
- Throws:
RemoteMetadataException
- If the REST URI cannot be determined based on the information given.
- The
-
getRemote
Same asgetRemote(Class)
except explicitly specifies the URI of the REST interface.See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
interfaceClass
- The interface to create a proxy for.rootUrl
- The URI of the REST interface.- Returns:
- The new proxy interface.
-
getRemote
public <T> T getRemote(Class<T> interfaceClass, Object rootUrl, Serializer serializer, Parser parser) Same asgetRemote(Class, Object)
but allows you to override the serializer and parser used.See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
interfaceClass
- The interface to create a proxy for.rootUrl
- 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.- Returns:
- The new proxy interface.
-
getRrpcInterface
Create a new proxy interface against an RRPC-style service.Remote interfaces are interfaces exposed on the server side using either the
RrpcServlet orRRPC REST methods.The URI to the REST interface is based on the following values:
- The
@Remote(path)
annotation on the interface (remote-path ). - The
rootUrl
on the client (root-url ). - The fully-qualified class name of the interface (
class-name ).
The URI calculation is as follows:
remote-path - If remote path is absolute.root-url/remote-path - If remote path is relative and root-url has been specified.root-url/class-name - If remote path is not specified.
If the information is not available to resolve to an absolute URI, a
RemoteMetadataException
is thrown.Notes:
- If you plan on using your proxy in a multi-threaded environment, you'll want to use an underlying pooling client connection manager.
See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
interfaceClass
- The interface to create a proxy for.- Returns:
- The new proxy interface.
- Throws:
RemoteMetadataException
- If the REST URI cannot be determined based on the information given.
- The
-
getRrpcInterface
Same asgetRrpcInterface(Class)
except explicitly specifies the URI of the REST interface.See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
interfaceClass
- The interface to create a proxy for.uri
- The URI of the REST interface.- Returns:
- The new proxy interface.
-
getRrpcInterface
public <T> T getRrpcInterface(Class<T> interfaceClass, Object uri, Serializer serializer, Parser parser) Same asgetRrpcInterface(Class, Object)
but allows you to override the serializer and parser used.See Also:
- Type Parameters:
T
- The interface to create a proxy for.- Parameters:
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.- Returns:
- The new proxy interface.
-
finalize
-
log
Logs a message.- Parameters:
level
- The log level.t
- Thrown exception. Can benull .msg
- The message.args
- Optional message arguments.
-
log
Logs a message.- Parameters:
level
- The log level.msg
- The message withMessageFormat
-style arguments.args
- The arguments.
-
getPartSerializer
Returns the part serializer associated with this client.- Returns:
- The part serializer associated with this client.
-
getPartParser
Returns the part parser associated with this client.- Returns:
- The part parser associated with this client.
-
getPartSerializer
Returns the part serializer instance of the specified type.- Parameters:
c
- The part serializer class.- Returns:
- The part serializer.
-
getPartParser
Returns the part parser instance of the specified type.- Parameters:
c
- The part parser class.- Returns:
- The part parser.
-
isSkipEmptyHeaderData
Returnstrue if empty request header values should be ignored.- Returns:
true if empty request header values should be ignored.
-
isSkipEmptyQueryData
Returnstrue if empty request query parameter values should be ignored.- Returns:
true if empty request query parameter values should be ignored.
-
isSkipEmptyFormData
Returnstrue if empty request form-data parameter values should be ignored.- Returns:
true if empty request form-data parameter values should be ignored.
-
createHeaderData
Creates a mutable copy of the header data defined on this client.Used during the construction of
RestRequest
objects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
createQueryData
Creates a mutable copy of the query data defined on this client.Used during the construction of
RestRequest
objects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
createFormData
Creates a mutable copy of the form data defined on this client.Used during the construction of
RestRequest
objects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
createPathData
Creates a mutable copy of the path data defined on this client.Used during the construction of
RestRequest
objects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
onCallInit
Interceptor method called immediately after the RestRequest object is created and all headers/query/form-data has been copied from the client.Subclasses can override this method to intercept the request and perform special modifications.
See Also:
- Parameters:
req
- The HTTP request.- Throws:
RestCallException
- If any of the interceptors threw an exception.
-
onCallConnect
Interceptor method called immediately after an HTTP response has been received.Subclasses can override this method to intercept the response and perform special modifications.
See Also:
- Parameters:
req
- The HTTP request.res
- The HTTP response.- Throws:
RestCallException
- If any of the interceptors threw an exception.
-
onCallClose
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.Subclasses can override this method to handle any cleanup operations.
See Also:
- Parameters:
req
- The HTTP request.res
- The HTTP response.- Throws:
RestCallException
- If any of the interceptors threw an exception.
-
getParams
Deprecated.UseRequestConfig
.Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.- Specified by:
getParams
in interfaceHttpClient
- Returns:
- The default parameters.
-
getConnectionManager
Deprecated.UseHttpClientBuilder
.Obtains the connection manager used by this client.- Specified by:
getConnectionManager
in interfaceHttpClient
- Returns:
- The connection manager.
-
getHttpClientConnectionManager
Returns the connection manager if one was specified in the client builder.- Returns:
- The connection manager. May be
null .
-
execute
Executes HTTP request using the default context.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
request
- The request to execute.- Returns:
- The response to the request.
This is always a final response, never an intermediate response with an 1xx status code.
Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. - Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException Executes HTTP request using the given context.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
request
- The request to execute.context
- The context to use for the execution, ornull to use the default context.- Returns:
- The response to the request.
This is always a final response, never an intermediate response with an 1xx status code.
Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. - Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException Executes HTTP request using the default context.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
target
- The target host for the request.
Implementations may acceptnull if they can still determine a route, for example to a default target or by inspecting the request.request
- The request to execute.- Returns:
- The response to the request.
This is always a final response, never an intermediate response with an 1xx status code.
Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. - Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException Executes HTTP request using the given context.Notes:
- This method gets passed on directly to the underlying
HttpClient
class. - The
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. - The
RestCallHandler
interface can also be implemented to intercept this method.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
target
- The target host for the request.
Implementations may acceptnull if they can still determine a route, for example to a default target or by inspecting the request.request
- The request to execute.context
- The context to use for the execution, ornull to use the default context.- Returns:
- The response to the request.
This is always a final response, never an intermediate response with an 1xx status code.
Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. - Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException Executes HTTP request using the default context and processes the response using the given response handler.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.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
request
- The request to execute.responseHandler
- The response handler.- Returns:
- Object returned by response handler.
- Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException Executes HTTP request using the given context and processes the response using the given response handler.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.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
request
- The request to execute.responseHandler
- The response handler.context
- The context to use for the execution, ornull to use the default context.- Returns:
- The response object as generated by the response handler.
- Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException Executes HTTP request to the target using the default context and processes the response using the given response handler.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.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
target
- The target host for the request.
Implementations may acceptnull if they can still determine a route, for example to a default target or by inspecting the request.request
- The request to execute.responseHandler
- The response handler.- Returns:
- The response object as generated by the response handler.
- Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
execute
public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException Executes a request using the default context and processes the response using the given response handler.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.Notes:
- This method gets passed on directly to the underlying
HttpClient
class.
- Specified by:
execute
in interfaceHttpClient
- Parameters:
target
- The target host for the request.
Implementations may acceptnull if they can still determine a route, for example to a default target or by inspecting the request.request
- The request to execute.responseHandler
- The response handler.context
- The context to use for the execution, ornull to use the default context.- Returns:
- The response object as generated by the response handler.
- Throws:
IOException
- In case of a problem or the connection was aborted.ClientProtocolException
- In case of an http protocol error.
- This method gets passed on directly to the underlying
-
properties
Description copied from class:Context
Returns the properties on this bean as a map for debugging.- Overrides:
properties
in classBeanContextable
- Returns:
- The properties on this bean as a map for debugging.
-
HttpClientBuilder
.