|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectgroovyx.net.http.HTTPBuilder
public class HTTPBuilder
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.
def http = new HTTPBuilder('http://www.google.com') http.get( path:'/search', 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:
http.request(GET,TEXT) { req -> response.success = { resp, stream -> println 'my response handler!' assert resp.statusLine.statusCode == 200 println resp.statusLine //System.out << stream // print response stream } response.'401' = { resp -> println 'access denied' } }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 ) { url.path = '/ajax/services/search/web' url.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}" } } }
Nested Class Summary | |
---|---|
protected class |
HTTPBuilder.SendDelegate
Encloses all properties and method calls used within the HTTPBuilder#request(URI, Method, ContentType, Closure) 'config'
closure argument. |
Field Summary | |
---|---|
protected AuthConfig |
auth
|
protected AbstractHttpClient |
client
|
protected ContentEncodingRegistry |
contentEncodingHandler
|
protected Object |
defaultContentType
|
protected Map<String,String> |
defaultRequestHeaders
|
protected Map<String,Closure> |
defaultResponseHandlers
|
protected URI |
defaultURI
|
protected EncoderRegistry |
encoders
|
protected ParserRegistry |
parsers
|
Constructor Summary | |
---|---|
HTTPBuilder()
|
|
HTTPBuilder(Object defaultURL)
Give a default URL to be used for all request methods that don't explicitly take a URL parameter. |
|
HTTPBuilder(Object defaultURL,
Object defaultContentType)
Give a default URL to be used for all request methods that don't explicitly take a URL parameter, and a default content-type to be used for request encoding and response parsing. |
Method Summary | |
---|---|
protected Map<String,Closure> |
buildDefaultResponseHandlers()
|
protected void |
defaultFailureHandler(HttpResponse resp)
This is the default response.failure handler. |
protected void |
defaultSuccessHandler(HttpResponse resp)
This is the default response.success handler. |
protected Object |
doRequest(HTTPBuilder.SendDelegate delegate)
|
protected Object |
doRequest(URI uri,
Method method,
Object contentType,
Closure configClosure)
|
Object |
get(Map<String,?> args,
Closure responseClosure)
Convenience method to perform an HTTP GET. |
AuthConfig |
getAuth()
Used to access the AuthConfig handler used to configure common
authentication mechanism. |
AbstractHttpClient |
getClient()
Return the underlying HTTPClient that is used to handle HTTP requests. |
Map<String,Closure> |
getEncoder()
Retrieve the map of registered request content-type encoders. |
Map<String,Closure> |
getHandler()
Retrieve the map of response code handlers. |
Map<String,String> |
getHeaders()
Get the map of default headers that will be added to all requests. |
Map<String,Closure> |
getParser()
Retrieve the map of registered response content-type parsers. |
Object |
getURL()
Get the default URL used for requests that do not explicitly take a url param. |
Object |
post(Map<String,?> args,
Closure responseClosure)
Convenience method to perform an HTTP form POST. |
Object |
request(Method m,
Closure configClosure)
|
Object |
request(Method m,
Object contentType,
Closure configClosure)
|
Object |
request(Object uri,
Method method,
Object contentType,
Closure configClosure)
Make a request for the given HTTP method and content-type, with additional options configured in the configClosure . |
void |
setAuthConfig(AuthConfig ac)
Set an alternative AuthConfig implementation to handle
authorization. |
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 |
setEncoderRegistry(EncoderRegistry er)
Set a custom registry used to handle different request content-type s. |
void |
setHeaders(Map<?,?> headers)
Set the default headers to add to all requests made by this builder instance. |
void |
setParserRegistry(ParserRegistry pr)
Set a custom registry used to handle different response content-type s |
void |
setURL(Object url)
Set the default URL used for requests that do not explicitly take a url param. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
protected AbstractHttpClient client
protected URI defaultURI
protected AuthConfig auth
protected Object defaultContentType
protected final Map<String,Closure> defaultResponseHandlers
protected ContentEncodingRegistry contentEncodingHandler
protected final Map<String,String> defaultRequestHeaders
protected EncoderRegistry encoders
protected ParserRegistry parsers
Constructor Detail |
---|
public HTTPBuilder()
public HTTPBuilder(Object defaultURL) throws URISyntaxException
defaultURL
- either a URL
, URI
or String
URISyntaxException
- if the URL was not parse-ablepublic HTTPBuilder(Object defaultURL, Object defaultContentType) throws URISyntaxException
defaultURL
- either a URL
, URI
or StringdefaultContentType
- content-type string. See ContentType
for common types.
URISyntaxException
- if the URL was not parse-ableMethod Detail |
---|
public Object get(Map<String,?> args, Closure responseClosure) throws ClientProtocolException, IOException, URISyntaxException
default
failure handler
throws an HttpResponseException
args
- see HTTPBuilder.SendDelegate.setPropertiesFromMap(Map)
responseClosure
- code to handle a successful HTTP response
ClientProtocolException
IOException
URISyntaxException
public Object post(Map<String,?> args, Closure responseClosure) throws URISyntaxException, 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.SendDelegate.setPropertiesFromMap(Map)
responseClosure
- code to handle a successful HTTP response
ClientProtocolException
IOException
URISyntaxException
public Object request(Method m, Closure configClosure) throws ClientProtocolException, IOException
ClientProtocolException
IOException
public Object request(Method m, Object contentType, Closure configClosure) throws ClientProtocolException, IOException
ClientProtocolException
IOException
public Object request(Object uri, Method method, Object contentType, Closure configClosure) throws ClientProtocolException, IOException, URISyntaxException
configClosure
. See
HTTPBuilder.SendDelegate
for options.
uri
- either a URI, URL, or Stringmethod
- HTTP method
contentType
- either a ContentType
or valid content-type string.configClosure
- closure from which to configure options like
path
,
request parameters
,
headers
,
request body
and
response handlers
.
IllegalAccessException
InstantiationException
ClientProtocolException
IOException
URISyntaxException
- if a URI string or URL was invalid.protected Object doRequest(URI uri, Method method, Object contentType, Closure configClosure) throws ClientProtocolException, IOException
ClientProtocolException
IOException
protected Object doRequest(HTTPBuilder.SendDelegate delegate) throws ClientProtocolException, IOException
ClientProtocolException
IOException
protected Map<String,Closure> buildDefaultResponseHandlers()
protected void defaultSuccessHandler(HttpResponse resp) throws IllegalStateException, IOException
response.success
handler. It will be
executed if no status-code-specific handler is set (i.e.
response.'200'= {..}
). This simply prints the status line
and the response stream to System.out
. In most cases you
will want to define a response.success = {...}
handler from
the request closure, which will replace this method.
resp
-
IllegalStateException
IOException
protected void defaultFailureHandler(HttpResponse 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 a 4xx and 5xx status response.
resp
-
HttpResponseException
public Map<String,Closure> getHandler()
builder.handler.'401' = { resp -> println "${resp.statusLine}" }
Status
public Map<String,Closure> getParser()
builder.parser.'text/javascript' = { resp -> return resp.entity.content // just returns an InputStream }
public Map<String,Closure> getEncoder()
builder.encoder.'text/javascript' = { body -> def json = body.call( new JsonGroovyBuilder() ) return new StringEntity( json.toString() ) }
public void setContentType(Object ct)
ContentType
enum holds
some common content-types that may be used, i.e. import static ContentType.* builder.contentType = XML
ct
- either a ContentType
or string value (i.e. "text/xml"
.)EncoderRegistry
,
ParserRegistry
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 setURL(Object url) throws URISyntaxException
url
param.
url
- a URL, URI, or String
URISyntaxException
public Object getURL()
url
param.
URL
instance. Note that the return type is Object
simply so that it matches with its JavaBean setURL(Object)
counterpart.public void setHeaders(Map<?,?> headers)
headers
- map of header names & values.public Map<String,String> getHeaders()
public AbstractHttpClient getClient()
public AuthConfig getAuth()
AuthConfig
handler used to configure common
authentication mechanism. Example:
builder.auth.basic( 'myUser', 'somePassword' )
public void setAuthConfig(AuthConfig ac)
AuthConfig
implementation to handle
authorization.
ac
- instance to use.public void setEncoderRegistry(EncoderRegistry er)
content-type
s.
er
- public void setParserRegistry(ParserRegistry pr)
content-type
s
pr
- public void setContentEncodingRegistry(ContentEncodingRegistry cer)
content-encoding
types in responses.
cer
-
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |