Skip to content
Tambapps edited this page Jul 10, 2022 · 18 revisions

HyperPoet

HyperPoet is a Groovy-friendly HTTP Client library written in Java 8. It is backed by OkHttp. Note that the term 'client' will often be replaced by 'poet' in this documentation.

The main goal of this library is to be able to perform HTTP requests with as less code as possible.

For that, several functionalities were implemented such as

  • Automatic response body parsing : The poet automatically parse the response's data given its Content-Type header. You can also add/modify custom parsers.

  • Automatic request body composing : The client/poet automatically compose the request's body (if any) given its content type. You can also add/modify custom composers.

Performing requests

The HttpPoet provides functions to perform common HTTP requests (GET, PUT, POST, PATCH, DELETE) and a request(..) function to perform a request with a custom HTTP method. There are two ways to perform request with this poet

Retrieve the response directly

You don't need to worry about anything but the response's data, you can perform a request just by specifying the url path (and optionally some additional parameters). This kind of call will directly return the parsed response, or throw an exception if the response isn't successful (response code < 200 or >= 300).

poet = new HttpPoet(url: API_URL, acceptContentType: ContentType.JSON)
def post = poet.get("/post/1")
println post

Handle the response yourself

If you want to have direct control on how to handle the response, you can provide a closure that will handle it

poet = new HttpPoet(url: API_URL, contentType: ContentType.JSON, acceptContentType: ContentType.JSON)
def data = poet.get("/post/1") { okhttp3.Response response ->
  if (response.isSuccessful()) {
    return new JsonSlurper().parseText(response.body().string())
  } else {
    return null
  }
}

Post data

Post method call is very similar to get. You just have to additionally specify the request body

def poet = new HttpPoet(url: API_URL, contentType: ContentType.JSON, acceptContentType: ContentType.JSON)
def newPost = [title: 'a new post', author: 'me@gmail.com', body: 'This is new!']
try {
  poet.post("/posts", body: newPost)
} catch (ErrorResponseException e) {
  println "Couldn't create new post!"
}

Multipart request

poet.post("/upload-file", contentType: ContentType.MULTIPART_FORM, body: [file: new FormData(value: new File('some.file'), contentType: ContentType.BINARY)])

Performing HTTP requests without specifying the path

You can also perform requests without specifying the path at all

// HTTP method and endpoint are determined by the invoked method's name
def post = poet.getPost(1)

// translated into POST /posts
poet.createPost(newPost)

You can learn more about that on the PoeticInvoker section

Clone this wiki locally