Class RestClient
- All Implemented Interfaces:
Closeable,AutoCloseable,HttpClient
- 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:
RestClientextends HttpClient, createsRestRequestobjects.RestRequestextends HttpUriRequest, createsRestResponseobjects.RestResponsecreatesResponseContentandResponseHeaderobjects.ResponseContentextends HttpEntityResponseHeaderextends 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 theSerializerdefined on the client or request. -
Reader- Raw contents ofReaderwill be serialized to remote resource. -
InputStream- Raw contents ofInputStreamwill 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:
RestResponsegetStatusLine()returns StatusLinegetStatusCode()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:
RestResponsegetHeaders(String)returns ResponseHeader[]getFirstHeader(String)returns ResponseHeadergetLastHeader(String)returns ResponseHeadergetAllHeaders()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:
ResponseHeaderisPresent()returns boolean asString()returns Stringas(Type,Type...)returns Tas(Class<T>)returns TasMatcher(Pattern)returns MatcherasMatcher(String)returns MatcherasHeader(Class<Textends BasicHeader> c)returns BasicHeaderasStringHeader()returns BasicStringHeaderasIntegerHeader()returns BasicIntegerHeaderasLongHeader()returns BasicLongHeaderasDateHeader()returns BasicDateHeaderasCsvHeader()returns BasicCsvHeaderasEntityTagsHeader()returns BasicEntityTagsHeaderasStringRangesHeader()returns BasicStringRangesHeaderasUriHeader()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:
RestResponsegetContent()returns ResponseContent
The ResponseContent class extends from the HttpClient HttpEntity class and provides several convenience
methods:
ResponseContentasInputStream()returns InputStreamasReader()returns ReaderasReader(Charset)returns ReaderpipeTo(OutputStream)returns RestResponsepipeTo(Writer)returns RestResponseas(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 ObjectRestasObjectRest()returns ObjectRestasMatcher(Pattern)returns MatcherasMatcher(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.BuilderRestCallHandlerrun(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:
RestClientgetRemote(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.BuilderhttpClientBuilder(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
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final booleanprotected final PartListprotected final HeaderListprotected final CloseableHttpClientprotected final booleanprotected final RestCallInterceptor[]protected final booleanprotected final DetailLevelprotected final Levelprotected final BiPredicate<RestRequest,RestResponse> protected final ParserSetprotected final HttpPartParserprotected final HttpPartSerializerprotected final PartListprotected final PartListprotected final SerializerSetprotected final booleanprotected final booleanprotected final booleanprotected final UrlEncodingSerializerFields inherited from class org.apache.juneau.BeanContextable
beanContextFields inherited from class org.apache.juneau.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionPerforms a REST call where the entire call is specified in a simple string.voidclose()CallsCloseable.close()on the underlyingCloseableHttpClient.voidSame asclose(), but ignores any exceptions.copy()Creates a builder from this context object.static RestClient.Buildercreate()Instantiates a new clean-slateRestClient.Builderobject.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 RestRequestcreateRequest(URI uri, String method, boolean hasBody) Creates aRestRequestobject from the specifiedHttpRequestobject.protected RestResponsecreateResponse(RestRequest request, HttpResponse httpResponse, Parser parser) Creates aRestResponseobject from the specifiedHttpResponseobject.Perform aDELETE request against the specified URI.execute(HttpUriRequest request) Executes HTTP request using the default context.<T> Texecute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) Executes HTTP request using the default context and processes the response using the given response handler.<T> Texecute(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> Texecute(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> Texecute(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 voidfinalize()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 HttpPartParserReturns the part parser associated with this client.protected HttpPartParsergetPartParser(Class<? extends HttpPartParser> c) Returns the part parser instance of the specified type.protected HttpPartSerializerReturns the part serializer associated with this client.protected HttpPartSerializergetPartSerializer(Class<? extends HttpPartSerializer> c) Returns the part serializer instance of the specified type.<T> TCreate a new proxy interface against a 3rd-party REST interface.<T> TSame asgetRemote(Class)except explicitly specifies the URI of the REST interface.<T> TgetRemote(Class<T> interfaceClass, Object rootUrl, Serializer serializer, Parser parser) Same asgetRemote(Class, Object)but allows you to override the serializer and parser used.<T> TgetRrpcInterface(Class<T> interfaceClass) Create a new proxy interface against an RRPC-style service.<T> TgetRrpcInterface(Class<T> interfaceClass, Object uri) Same asgetRrpcInterface(Class)except explicitly specifies the URI of the REST interface.<T> TgetRrpcInterface(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 voidinit()Gets called add the end of the constructor call to perform any post-initialization.protected booleanReturnstrue if empty request form-data parameter values should be ignored.protected booleanReturnstrue if empty request header values should be ignored.protected booleanReturnstrue if empty request query parameter values should be ignored.protected voidLogs a message.protected voidLogs a message.protected voidonCallClose(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 voidonCallConnect(RestRequest req, RestResponse res) Interceptor method called immediately after an HTTP response has been received.protected voidonCallInit(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.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 RestRequestrequest(RestOperation op) Perform an arbitrary request against the specified URI.protected HttpResponserun(HttpHost target, HttpRequest request, HttpContext context) Entrypoint for executing all requests and returning a response.Methods inherited from class org.apache.juneau.BeanContextable
getBeanContextMethods inherited from class org.apache.juneau.Context
createBuilder, createSession, getAnnotationProvider, getSession, init, isDebug, toString
-
Field Details
-
detectLeaks
-
ignoreErrors
-
keepHttpClientOpen
-
skipEmptyFormData
-
skipEmptyHeaderData
-
skipEmptyQueryData
-
logRequestsPredicate
-
httpClient
-
logRequests
-
headerData
-
partParser
-
partSerializer
-
logRequestsLevel
-
formData
-
pathData
-
queryData
-
parsers
-
interceptors
-
serializers
-
urlEncodingSerializer
-
-
Constructor Details
-
RestClient
Constructor.- Parameters:
builder- The builder for this client.
-
-
Method Details
-
create
Instantiates a new clean-slateRestClient.Builderobject.- Returns:
- A new
RestClient.Builderobject.
-
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.
Can benull or empty (treated as empty string, will result in an invalid request).- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- REST call failed.
-
-
close
CallsCloseable.close()on the underlyingCloseableHttpClient.It's good practice to call this method after the client is no longer used.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IOException- Thrown by underlying stream.
-
closeQuietly
Same asclose(), but ignores any exceptions. -
copy
Description copied from class:ContextCreates a builder from this context object.Builders are used to define new contexts (e.g. serializers, parsers) based on existing configurations.
-
createFormData
Creates a mutable copy of the form data defined on this client.Used during the construction of
RestRequestobjects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
createHeaderData
Creates a mutable copy of the header data defined on this client.Used during the construction of
RestRequestobjects.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
RestRequestobjects.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
RestRequestobjects.Subclasses can override this method to provide their own builder.
- Returns:
- A new builder.
-
delete
Perform aDELETE request against the specified URI.- Parameters:
uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- If any authentication errors occurred.
-
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
HttpClientclass.
- Specified by:
executein 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
HttpClientclass. - 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
RestCallHandlerinterface can also be implemented to intercept this method.
- Specified by:
executein 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(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
ResponseHandlersfrom having to manage resource deallocation internally.Notes:
- This method gets passed on directly to the underlying
HttpClientclass.
- Specified by:
executein 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
ResponseHandlersfrom having to manage resource deallocation internally.Notes:
- This method gets passed on directly to the underlying
HttpClientclass.
- Specified by:
executein 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
-
execute
Executes HTTP request using the default context.Notes:
- This method gets passed on directly to the underlying
HttpClientclass.
- Specified by:
executein 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
HttpClientclass.
- Specified by:
executein 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 <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
ResponseHandlersfrom having to manage resource deallocation internally.Notes:
- This method gets passed on directly to the underlying
HttpClientclass.
- Specified by:
executein 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
ResponseHandlersfrom having to manage resource deallocation internally.Notes:
- This method gets passed on directly to the underlying
HttpClientclass.
- Specified by:
executein 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
-
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:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject 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:URIBuilderURIURLStringObject- 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.NameValuePairarray - 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 aSerializedEntityusingUrlEncodingSerializerto serialize.Supplier- A supplier of anything on this list.
- Returns:
- A
RestRequestobject 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:URIBuilderURIURLStringObject- 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 toBasicPartobjects.- Returns:
- A
RestRequestobject 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
RestRequestobject 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 specified URI.- Parameters:
uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- If any authentication errors occurred.
-
getConnectionManager
Deprecated.UseHttpClientBuilder.Obtains the connection manager used by this client.- Specified by:
getConnectionManagerin 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 .
-
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:
getParamsin interfaceHttpClient- Returns:
- The default parameters.
-
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
rootUrlon 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
RemoteMetadataExceptionis 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.
Cannot benull .- 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.
Cannot benull .rootUrl- The URI of the REST interface.
Can benull (will use the root URL from the client builder if set).- 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.
Cannot benull .rootUrl- The URI of the REST interface.
Can benull (will use the root URL from the client builder if set).serializer- The serializer used to serialize POJOs to the body of the HTTP request.
Can benull (will use the default serializer from the client).parser- The parser used to parse POJOs from the body of the HTTP response.
Can benull (will use the default parser from the client).- 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
rootUrlon 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
RemoteMetadataExceptionis 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.
Cannot benull .- 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.
Cannot benull .uri- The URI of the REST interface.
Can benull (will use the root URL from the client builder if set).- 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.
Cannot benull .uri- The URI of the REST interface.
Can benull (will use the root URL from the client builder if set).serializer- The serializer used to serialize POJOs to the body of the HTTP request.
Can benull (will use the default serializer from the client).parser- The parser used to parse POJOs from the body of the HTTP response.
Can benull (will use the default parser from the client).- Returns:
- The new proxy interface.
-
head
Perform aHEAD request against the specified URI.- Parameters:
uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject 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:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject 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:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- REST call failed.
-
patch
Perform aPATCH request against the specified URI.- Parameters:
uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- 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 ofReaderwill be serialized to remote resource. -
InputStream- Raw contents ofInputStreamwill 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 theSerializerregistered with theRestClient. -
PartList- Converted to a URL-encoded FORM post. -
Supplier- A supplier of anything on this list.
-
- Returns:
- A
RestRequestobject 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:URIBuilderURIURLStringObject- 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
RestRequestobject 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:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- REST call failed.
- Use
-
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:URIBuilderURIURLStringObject- 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 ofReaderwill be serialized to remote resource. -
InputStream- Raw contents ofInputStreamwill be serialized to remote resource. -
Object- POJO to be converted to text using theSerializerregistered 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
RestRequestobject 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:URIBuilderURIURLStringObject- 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
RestRequestobject 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:URIBuilderURIURLStringObject- Converted toString usingtoString()
- Returns:
- A
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- REST call failed.
-
put
Perform aPUT request against the specified URI.- Parameters:
uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- 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 ofReaderwill be serialized to remote resource. -
InputStream- Raw contents ofInputStreamwill be serialized to remote resource. -
Object- POJO to be converted to text using theSerializerregistered 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
RestRequestobject 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:URIBuilderURIURLStringObject- 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
RestRequestobject 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.
Cannot benull .uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
Can benull (will result in an invalid request).- Returns:
- A
RestRequestobject 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" ).
Cannot benull .uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
Can benull (will result in an invalid request).hasBody- Boolean flag indicating if the specified request has content associated with it.- Returns:
- A
RestRequestobject 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.
Cannot benull .uri- The URI of the remote REST resource.
Can be any of the following types:URIBuilderURIURLStringObject- Converted toString usingtoString()
Can benull (will result in an invalid request).body- The HTTP body content. Can be of the following types:-
Reader- Raw contents ofReaderwill be serialized to remote resource. -
InputStream- Raw contents ofInputStreamwill 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 theSerializerregistered with theRestClient. -
PartList- Converted to a URL-encoded FORM post. -
Supplier- A supplier of anything on this list.
-
- Returns:
- A
RestRequestobject 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 aRestRequestobject from the specifiedHttpRequestobject.Subclasses can override this method to provide their own specialized
RestRequestobjects.- Parameters:
uri- The target.method- The HTTP method (uppercase).hasBody- Whether this method has a request entity.- Returns:
- A new
RestRequestobject. - 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 aRestResponseobject from the specifiedHttpResponseobject.Subclasses can override this method to provide their own specialized
RestResponseobjects.- 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
RestResponseobject. - Throws:
RestCallException- If an exception or non-200 response code occurred during the connection attempt.
-
finalize
-
getPartParser
Returns the part parser associated with this client.- Returns:
- The part parser associated with this client.
-
getPartParser
Returns the part parser instance of the specified type.- Parameters:
c- The part parser class.- Returns:
- The part parser.
-
getPartSerializer
Returns the part serializer associated with this client.- Returns:
- The part serializer associated with this client.
-
getPartSerializer
Returns the part serializer instance of the specified type.- Parameters:
c- The part serializer class.- Returns:
- The part serializer.
-
init
Gets called add the end of the constructor call to perform any post-initialization. -
isSkipEmptyFormData
Returnstrue if empty request form-data parameter values should be ignored.- Returns:
true if empty request form-data parameter values should be ignored.
-
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.
-
log
Logs a message.- Parameters:
level- The log level.msg- The message withMessageFormat-style arguments.args- The arguments.
-
log
Logs a message.- Parameters:
level- The log level.t- Thrown exception.
Can benull (no exception stack trace will be logged).msg- The message.args- Optional message arguments.
-
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.
-
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.
-
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.
-
properties
Description copied from class:ContextReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classBeanContextable- Returns:
- The properties on this bean as a map for debugging.
-
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
RestRequestobject that can be further tailored before executing the request and getting the response as a parsed object. - Throws:
RestCallException- If any authentication errors occurred.
-
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.
-
HttpClientBuilder.