public abstract class HTTPBuilder extends Object
Groovy DSL for easily making HTTP requests, and handling request and response data. This class adds a number of convenience mechanisms built on top of Apache HTTPClient for things like URL-encoded POSTs and REST requests that require building and parsing JSON or XML. Convenient access to a few common authentication methods is also available.
HTTPBuilder has properties for default headers, URI, contentType, etc.
All of these values are also assignable (and in many cases, in much finer
detail) from the HTTPBuilder.RequestConfigDelegate
as well. In any cases where the value
is not set on the delegate (from within a request closure,) the builder's
default value is used.
For instance, any methods that do not take a uri
parameter
assume you will set the uri
property in the request closure or
use HTTPBuilder's assigned default URI
.
By default, HTTPBuilder uses ContentType.ANY
as the default
content-type. This means the value of the request's Accept
header is */*
, and the response parser is determined
based on the response content-type
header.
If any contentType is given (either in
setContentType(Object)
or as a request method parameter), the
builder will attempt to parse the response using that content-type,
regardless of what the server actually responds with.
def http = new HTTPBuilder('http://www.google.com') http.get( path : '/search', contentType : TEXT, query : [q:'Groovy'] ) { resp, reader -> println "response status: ${resp.statusLine}" println 'Response data: -----' System.out << reader println '\n--------------------' }
Long form for other HTTP methods, and response-code-specific handlers. This is roughly equivalent to the above example.
def http = new HTTPBuilder('http://www.google.com/search?q=groovy') http.request( GET, TEXT ) { req -> // executed for all successful responses: response.success = { resp, reader -> println 'my response handler!' assert resp.statusLine.statusCode == 200 println resp.statusLine System.out << reader // print response stream } // executed only if the response status code is 401: response.'404' = { resp -> println 'not found!' } }
You can also set a default response handler called for any status code > 399 that is not matched to a specific handler. Setting the value outside a request closure means it will apply to all future requests with this HTTPBuilder instance:
http.handler.failure = { resp -> println "Unexpected failure: ${resp.statusLine}" }
And... Automatic response parsing for registered content types!
http.request( 'http://ajax.googleapis.com', GET, JSON ) { uri.path = '/ajax/services/search/web' uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ] response.success = { resp, json -> assert json.size() == 3 println "Query response: " json.responseData.results.each { println " ${it.titleNoFormatting} : ${it.visibleUrl}" } } }
Modifier and Type | Class and Description |
---|---|
protected class |
HTTPBuilder.RequestConfigDelegate
Encloses all properties and method calls used within the
HTTPBuilder#request(Object, HttpRequestFactory, Object, Closure) 'config'
closure argument. |
Modifier and Type | Field and Description |
---|---|
protected AuthConfig |
auth |
protected org.apache.http.impl.client.AbstractHttpClient |
client |
protected ContentEncodingRegistry |
contentEncodingHandler |
protected Object |
defaultContentType |
protected Object |
defaultRequestContentType |
protected Map<Object,Object> |
defaultRequestHeaders |
protected Map<Object,groovy.lang.Closure> |
defaultResponseHandlers |
protected URIBuilder |
defaultURI |
protected EncoderRegistry |
encoders |
protected org.apache.commons.logging.Log |
log |
protected HttpResponseContentTypeFinder |
parsers |
Constructor and Description |
---|
HTTPBuilder(boolean urlEncodingEnabled,
EncoderConfig encoderConfig,
DecoderConfig decoderConfig,
OAuthConfig oAuthConfig,
org.apache.http.impl.client.AbstractHttpClient client) |
HTTPBuilder(Object defaultURI,
boolean urlEncodingEnabled,
EncoderConfig encoderConfig,
DecoderConfig decoderConfig,
OAuthConfig oAuthConfig,
org.apache.http.impl.client.AbstractHttpClient client)
Give a default URI to be used for all request methods that don't
explicitly take a URI parameter.
|
HTTPBuilder(Object defaultURI,
Object defaultContentType,
boolean urlEncodingEnabled,
EncoderConfig encoderConfig,
DecoderConfig decoderConfig,
OAuthConfig oAuthConfig,
org.apache.http.impl.client.AbstractHttpClient client)
Give a default URI to be used for all request methods that don't
explicitly take a URI parameter, and a default content-type to be used
for request encoding and response parsing.
|
Modifier and Type | Method and Description |
---|---|
protected Map<Object,groovy.lang.Closure> |
buildDefaultResponseHandlers()
|
protected void |
defaultFailureHandler(HttpResponseDecorator resp)
This is the default
response.failure handler. |
protected Object |
defaultSuccessHandler(HttpResponseDecorator resp,
Object parsedData)
This is the default
response.success handler. |
protected abstract Object |
doRequest(HTTPBuilder.RequestConfigDelegate delegate)
A copy of HTTP builders doRequest method with two exceptions.
|
protected Object |
doRequest(URI uri,
String method,
Object contentType,
boolean hasBody,
groovy.lang.Closure configClosure)
Create a
HTTPBuilder.RequestConfigDelegate from the given arguments, execute the
config closure, then pass the delegate to doRequest(RequestConfigDelegate) ,
which actually executes the request. |
Object |
get(Map<String,?> args)
Convenience method to perform an HTTP GET.
|
Object |
get(Map<String,?> args,
groovy.lang.Closure responseClosure)
Convenience method to perform an HTTP GET.
|
org.apache.http.impl.client.AbstractHttpClient |
getClient()
Return the underlying HTTPClient that is used to handle HTTP requests.
|
Object |
getContentType() |
Map<?,groovy.lang.Closure> |
getHandler()
Retrieve the map of response code handlers.
|
Map<?,?> |
getHeaders()
Get the map of default headers that will be added to all requests.
|
HttpResponseContentTypeFinder |
getParser()
Retrieve the map of registered response content-type parsers.
|
Object |
getUri()
Get the default URI used for requests that do not explicitly take a
uri param. |
protected Object |
parseResponse(org.apache.http.HttpResponse resp,
Object contentType)
Parse the response data based on the given content-type.
|
Object |
patch(Map<String,?> args)
Convenience method to perform an HTTP PATCH.
|
Object |
patch(Map<String,?> args,
groovy.lang.Closure responseClosure)
Convenience method to perform an HTTP form PATCH.
|
Object |
post(Map<String,?> args)
Convenience method to perform an HTTP POST.
|
Object |
post(Map<String,?> args,
groovy.lang.Closure responseClosure)
Convenience method to perform an HTTP form POST.
|
Object |
request(Object uri,
String method,
Object contentType,
boolean hasBody,
groovy.lang.Closure configClosure)
Make a request for the given HTTP method and content-type, with
additional options configured in the
configClosure . |
Object |
request(String method,
boolean hasBody,
groovy.lang.Closure configClosure)
Make an HTTP request to the default URI, and parse using the default
content-type.
|
Object |
request(String method,
Object contentType,
boolean hasBody,
groovy.lang.Closure configClosure)
Make an HTTP request using the default URI, with the given method,
content-type, and configuration.
|
void |
setContentEncoding(Object... encodings)
Set acceptable request and response content-encodings.
|
void |
setContentEncodingRegistry(ContentEncodingRegistry cer)
Set a custom registry used to handle different
content-encoding types in responses. |
void |
setContentType(Object ct)
Set the default content type that will be used to select the appropriate
request encoder and response parser.
|
void |
setHeaders(Map<?,?> headers)
Set the default headers to add to all requests made by this builder
instance.
|
void |
setProxy(String host,
int port,
String scheme)
Set the default HTTP proxy to be used for all requests.
|
void |
setUri(Object uri)
Set the default URI used for requests that do not explicitly take a
uri param. |
void |
shutdown()
Release any system resources held by this instance.
|
protected org.apache.http.impl.client.AbstractHttpClient client
protected URIBuilder defaultURI
protected AuthConfig auth
protected final org.apache.commons.logging.Log log
protected Object defaultContentType
protected Object defaultRequestContentType
protected ContentEncodingRegistry contentEncodingHandler
protected EncoderRegistry encoders
protected HttpResponseContentTypeFinder parsers
public HTTPBuilder(boolean urlEncodingEnabled, EncoderConfig encoderConfig, DecoderConfig decoderConfig, OAuthConfig oAuthConfig, org.apache.http.impl.client.AbstractHttpClient client)
public HTTPBuilder(Object defaultURI, boolean urlEncodingEnabled, EncoderConfig encoderConfig, DecoderConfig decoderConfig, OAuthConfig oAuthConfig, org.apache.http.impl.client.AbstractHttpClient client)
defaultURI
- either a URL
, URI
or object whose
toString()
produces a valid URI string. See
URIBuilder.convertToURI(Object)
.URISyntaxException
- if the given argument does not represent a valid URIpublic HTTPBuilder(Object defaultURI, Object defaultContentType, boolean urlEncodingEnabled, EncoderConfig encoderConfig, DecoderConfig decoderConfig, OAuthConfig oAuthConfig, org.apache.http.impl.client.AbstractHttpClient client) throws URISyntaxException
defaultURI
- either a URL
, URI
or object whose
toString()
produces a valid URI string. See
URIBuilder.convertToURI(Object)
.defaultContentType
- content-type string. See ContentType
for common types.URISyntaxException
- if the uri argument does not represent a valid URIpublic Object get(Map<String,?> args) throws org.apache.http.client.ClientProtocolException, IOException, URISyntaxException
Convenience method to perform an HTTP GET. It will use the HTTPBuilder's
registered response handlers
to handle success or
failure status codes. By default, the success
response
handler will attempt to parse the data and simply return the parsed
object.
Note: If using the default
, be sure to read the
caveat regarding streaming response data.success
response handler
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
URISyntaxException
- if a uri argument is given which does not
represent a valid URIIOException
org.apache.http.client.ClientProtocolException
getHandler()
,
defaultSuccessHandler(HttpResponseDecorator, Object)
,
defaultFailureHandler(HttpResponseDecorator)
public Object get(Map<String,?> args, groovy.lang.Closure responseClosure) throws org.apache.http.client.ClientProtocolException, IOException, URISyntaxException
Convenience method to perform an HTTP GET. The response closure will be called only on a successful response.
A 'failed' response (i.e. any HTTP status code > 399) will be handled
by the registered 'failure' handler. The
default failure handler
throws an HttpResponseException
.
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
responseClosure
- code to handle a successful HTTP responseorg.apache.http.client.ClientProtocolException
IOException
URISyntaxException
- if a uri argument is given which does not
represent a valid URIpublic Object post(Map<String,?> args) throws org.apache.http.client.ClientProtocolException, URISyntaxException, IOException
Convenience method to perform an HTTP POST. It will use the HTTPBuilder's
registered response handlers
to handle success or
failure status codes. By default, the success
response
handler will attempt to parse the data and simply return the parsed
object.
Note: If using the default
, be sure to read the
caveat regarding streaming response data.success
response handler
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
IOException
URISyntaxException
- if a uri argument is given which does not
represent a valid URIorg.apache.http.client.ClientProtocolException
getHandler()
,
defaultSuccessHandler(HttpResponseDecorator, Object)
,
defaultFailureHandler(HttpResponseDecorator)
public Object post(Map<String,?> args, groovy.lang.Closure responseClosure) throws URISyntaxException, org.apache.http.client.ClientProtocolException, IOException
Convenience method to perform an HTTP form POST. The response closure will be called only on a successful response.
A 'failed' response (i.e. any
HTTP status code > 399) will be handled by the registered 'failure'
handler. The default
failure handler
throws an HttpResponseException
.
The request body (specified by a body
named parameter)
will be converted to a url-encoded form string unless a different
requestContentType
named parameter is passed to this method.
(See EncoderRegistry.encodeForm(Map)
.)
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
responseClosure
- code to handle a successful HTTP responseorg.apache.http.client.ClientProtocolException
IOException
URISyntaxException
- if a uri argument is given which does not
represent a valid URIpublic Object patch(Map<String,?> args) throws org.apache.http.client.ClientProtocolException, URISyntaxException, IOException
Convenience method to perform an HTTP PATCH. It will use the HTTPBuilder's
registered response handlers
to handle success or
failure status codes. By default, the success
response
handler will attempt to parse the data and simply return the parsed
object.
Note: If using the default
, be sure to read the
caveat regarding streaming response data.success
response handler
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
IOException
URISyntaxException
- if a uri argument is given which does not
represent a valid URIorg.apache.http.client.ClientProtocolException
getHandler()
,
defaultSuccessHandler(HttpResponseDecorator, Object)
,
defaultFailureHandler(HttpResponseDecorator)
public Object patch(Map<String,?> args, groovy.lang.Closure responseClosure) throws URISyntaxException, org.apache.http.client.ClientProtocolException, IOException
Convenience method to perform an HTTP form PATCH. The response closure will be called only on a successful response.
A 'failed' response (i.e. any
HTTP status code > 399) will be handled by the registered 'failure'
handler. The default
failure handler
throws an HttpResponseException
.
The request body (specified by a body
named parameter)
will be converted to a url-encoded form string unless a different
requestContentType
named parameter is passed to this method.
(See EncoderRegistry.encodeForm(Map)
.)
args
- see HTTPBuilder.RequestConfigDelegate.setPropertiesFromMap(Map)
responseClosure
- code to handle a successful HTTP responseorg.apache.http.client.ClientProtocolException
IOException
URISyntaxException
- if a uri argument is given which does not
represent a valid URIpublic Object request(String method, boolean hasBody, groovy.lang.Closure configClosure) throws org.apache.http.client.ClientProtocolException, IOException
method
- HTTP method
configClosure
- request configuration optionsorg.apache.http.client.ClientProtocolException
IOException
#request(Object, HttpRequestFactory, Object, Closure)
public Object request(String method, Object contentType, boolean hasBody, groovy.lang.Closure configClosure) throws org.apache.http.client.ClientProtocolException, IOException
method
- HTTP method
contentType
- either a ContentType
or valid content-type string.configClosure
- request configuration optionsorg.apache.http.client.ClientProtocolException
IOException
#request(Object, HttpRequestFactory, Object, Closure)
public Object request(Object uri, String method, Object contentType, boolean hasBody, groovy.lang.Closure configClosure) throws org.apache.http.client.ClientProtocolException, IOException, URISyntaxException
configClosure
. See
HTTPBuilder.RequestConfigDelegate
for options.uri
- either a URL
, URI
or object whose
toString()
produces a valid URI string. See
URIBuilder.convertToURI(Object)
.method
- HTTP method
contentType
- either a ContentType
or valid content-type string.configClosure
- closure from which to configure options like
uri.path
,
request parameters
,
headers
,
request body
and
response handlers
.org.apache.http.client.ClientProtocolException
IOException
URISyntaxException
- if the uri argument does not represent a valid URIprotected Object doRequest(URI uri, String method, Object contentType, boolean hasBody, groovy.lang.Closure configClosure) throws IOException
HTTPBuilder.RequestConfigDelegate
from the given arguments, execute the
config closure, then pass the delegate to doRequest(RequestConfigDelegate)
,
which actually executes the request.IOException
protected abstract Object doRequest(HTTPBuilder.RequestConfigDelegate delegate) throws org.apache.http.client.ClientProtocolException, IOException
org.apache.http.client.ClientProtocolException
IOException
protected Object parseResponse(org.apache.http.HttpResponse resp, Object contentType) throws IOException
ContentType.ANY
, the
content-type
header from the response will be used to
determine how to parse the response.resp
- contentType
- null
if no parser could be found for this
content-type. The parser will also return null
if the
response does not contain any content (e.g. in response to a HEAD request).HttpResponseException
- if there is a error parsing the responseIOException
protected Map<Object,groovy.lang.Closure> buildDefaultResponseHandlers()
success
and
failure
status codes. This is used to populate
the handler map when a new HTTPBuilder instance is created.defaultSuccessHandler(HttpResponseDecorator, Object)
,
defaultFailureHandler(HttpResponseDecorator)
protected Object defaultSuccessHandler(HttpResponseDecorator resp, Object parsedData) throws ResponseParseException
This is the default response.success
handler. It will be
executed if the response is not handled by a status-code-specific handler
(i.e. response.'200'= {..}
) and no generic 'success' handler
is given (i.e. response.success = {..}
.) This handler simply
returns the parsed data from the response body. In most cases you will
probably want to define a response.success = {...}
handler
from the request closure, which will replace the response handler defined
by this method.
In practice, a user-supplied response handler closure is designed to handle streaming content so it can be read directly from the response stream without buffering, which will be much more efficient. Therefore, it is recommended that request method variants be used which explicitly accept a response handler closure in these cases.
resp
- HTTP responseparsedData
- parsed data as resolved from this instance's HttpResponseContentTypeFinder
ResponseParseException
- if there is an error buffering a streaming
response.protected void defaultFailureHandler(HttpResponseDecorator resp) throws HttpResponseException
response.failure
handler. It will be
executed if no status-code-specific handler is set (i.e.
response.'404'= {..}
). This default handler will throw a
HttpResponseException
when executed. In most cases you
will want to define your own response.failure = {...}
handler from the request closure, if you don't want an exception to be
thrown for 4xx and 5xx status responses.resp
- HttpResponseException
public Map<?,groovy.lang.Closure> getHandler()
builder.handler.'401' = { resp -> println "${resp.statusLine}" }
Status
public HttpResponseContentTypeFinder getParser()
builder.parser.'text/javascript' = { resp -> return resp.entity.content // just returns an InputStream }
public void setContentType(Object ct)
ContentType
enum holds
some common content-types that may be used, i.e. import static ContentType.* builder.contentType = XMLSetting the default content-type does three things:
request body
as this content-type. Calling HTTPBuilder.RequestConfigDelegate.setRequestContentType(String)
can override this
on a per-request basis.content-type
header that is sent in the
response.Accept
header to this content-type for all
requests (see ContentType.getAcceptHeader()
). Note
that any Accept
header explicitly set either in
setHeaders(Map)
or HTTPBuilder.RequestConfigDelegate.setHeaders(Map)
will override this value.Additionally, if the content-type is set to ContentType.ANY
,
HTTPBuilder will rely on the content-type
response
header to determine how to parse the response data. This allows the user
to rely on response headers if they are accurate, or ignore them and
forcibly use a certain response parser if so desired.
This value is a default and may always be overridden on a per-request
basis by using the #request(Method, Closure)
builder.request( Method, ContentType, Closure )} method or passing a
contentType
named parameter.
ct
- either a ContentType
or string value (i.e. "text/xml"
.)EncoderRegistry
,
HttpResponseContentTypeFinder
public Object getContentType()
public void setContentEncoding(Object... encodings)
encodings
- each Object should be either a
ContentEncoding.Type
value, or a content-encoding
string that is known by the ContentEncodingRegistry
ContentEncodingRegistry
public void setUri(Object uri) throws URISyntaxException
uri
param.uri
- either a URL
, URI
or object whose
toString()
produces a valid URI string. See
URIBuilder.convertToURI(Object)
.URISyntaxException
- if the uri argument does not represent a valid URIpublic Object getUri()
uri
param.URIBuilder
instance. Note that the return type is Object
simply so that it matches with its JavaBean setUri(Object)
counterpart.public void setHeaders(Map<?,?> headers)
headers
- map of header names & values.public Map<?,?> getHeaders()
public org.apache.http.impl.client.AbstractHttpClient getClient()
public void setContentEncodingRegistry(ContentEncodingRegistry cer)
content-encoding
types in responses.cer
- public void setProxy(String host, int port, String scheme)
host
- host name or IPport
- port, or -1 for the default portscheme
- usually "http" or "https," or null
for the defaultHttpHost.HttpHost(String, int, String)
public void shutdown()
ClientConnectionManager.shutdown()
Copyright © 2010–2019. All rights reserved.