A simple class which makes using REST services like the GitHub API really easy. This utilizes helpful features of Groovy while not relying on any heavier external libraries for HTTP communication.
To run this example, clone Jervis and execute ./gradlew console to bring up a Groovy Console with the classpath set up.
By default, JSON-based REST APIs are assumed. The response will automatically be parsed into a plain Java Object. In this example, a HashMap is returned.
import net.gleske.jervis.remotes.SimpleRestService
SimpleRestService.apiFetch(new URL('https://api.github.com/meta'))
So if you do not set the content type, then an application/json response will be assumed. If you do not want any response processing you can force no content type by passing a null HTTP request header value for Content-Type.
import net.gleske.jervis.remotes.SimpleRestService
SimpleRestService.apiFetch(new URL('http://www.example.com/'), ['Content-Type': null])
This client can send or receive binary data by using a special header Binary-Data. Compare this example with GZip
import java.net.HttpURLConnection
import net.gleske.jervis.remotes.SimpleRestService
import net.gleske.jervis.tools.GZip
import net.gleske.jervis.tools.SecurityIO
String username = 'some user'
String password = 'some pass'
// this example data will be compressed and uploaded to Nexus
String upload_data = 'hello world\n\nMy friend\n'
URL api_url = new URL('http://localhost:8081/repository/hosted-raw-repo/file.gz')
Map http_headers = [
Authorization: "Basic ${SecurityIO.encodeBase64("${username}:${password}")}",
Accept: '*/*',
Expect: '100-continue',
'Binary-Data': true
]
// make network call uploading or receiving binary data
HttpURLConnection response = SimpleRestService.apiFetch(
api_url,
http_headers,
'PUT',
'binary-data') { httpOutputStream ->
// wrap the output stream with compression
new GZip(httpOutputStream).withCloseable { gzip ->
gzip << upload_data
}
}
// get response message from Nexus
response.getHeaderFields()[null][0]
You can also use the Binary-Data special header to get back the raw HTTP request response so you can do your own custom processing.
import net.gleske.jervis.remotes.SimpleRestService
SimpleRestService.apiFetch(new URL('http://www.example.com/'), ['Binary-Data': true])
You would also do a similar request to download compressed data you uploaded to Nexus.
import java.net.HttpURLConnection
import java.util.zip.GZIPInputStream
import net.gleske.jervis.remotes.SimpleRestService
URL api_url = new URL('http://localhost:8081/repository/hosted-raw-repo/file.gz')
HttpURLConnection response = SimpleRestService.apiFetch(api_url, ['Binary-Data': true])
ByteArrayOutputStream plain = new ByteArrayOutputStream()
response.inputStream.withCloseable { is ->
new GZIPInputStream(is).withCloseable { gunzip ->
// decompress the downloaded text
plain << gunzip
}
}
assert plain.toString() == 'hello world\n\nMy friend\n'
| Type Params | Return Type | Name and description |
|---|---|---|
|
static String |
addTrailingSlash(String url, String suffix = '')Meant for flexibly setting API URLs, this will enforce a trailing slash and optionaly a suffix such as an API version applied to the URL. |
|
static def |
apiFetch(URL api_url, Map http_headers = [:], String http_method = 'GET', def data = '', Closure httpOutputStream = null)apiFetch() can be used to submit HTTP commands common to REST APIs. |
|
static String |
objToJson(def obj)A method for converting an object comprising of standard Java classes Map or List to a JSON String. |
Meant for flexibly setting API URLs, this will enforce a trailing slash and optionaly a suffix such as an API version applied to the URL.
url - Typically an API URL where a trailing slash will be added if
missing.suffix - Typically an API version path where a trailing slash will be
added if missing. If this option is provided, then it will
ensure url ends with the suffix and add it
if missing.apiFetch() can be used to submit HTTP commands common to REST APIs. If http_headers does not contain a Content-Type header, then application/json is assumed.
Extra behaviors are provided by special http_headers. These headers are not sent over HTTP but instead change the behavior of the response.
api_url - A URL of a REST endpoint in which to make an HTTP call.http_headers - HTTP headers to pass as part of the HTTP request. By
default only Content-Type: application/json HTTP
header will be set.http_method - The HTTP method or action to request from the server.
Currently supported methods include: GET, POST, PUT, DELETE,
and PATCH.data - Send String data to the remote connection via
OutputStream
Writer.httpOutputStream - A Closure in which an
OutputStream is passed as an
argument. This allows caller to write binary data to the
remote as part of the HTTP connection. The
httpOutputStream will only be called if
data is a non-zero length String.A method for converting an object comprising of standard Java classes Map or List to a JSON String.
obj - Any object.