HTTP Client #
The framework comes packaged with a very basic HTTP client. You can use this client for sending server to server requests, or even testing certain aspects of your application.
Creating the client #
To create a client, use the HttpClient.create() factory method:
HttpClient client = HttpClient.create("https://google.com")
This will create a client for the server at (in this case) google.com
.
Creating a request #
Once the client has been created, you can create requests to send to the server.
HttpClientRequest request = client.createRequest()
If no path argument is specified when invoking createRequest()
it will use the root path (/
) and the HTTP method
will default to GET
.
Sending a request #
Once your request has been created, use the httpClient.send()
method to send it. This will return an instance of
HttpClientResponse
.
HttpClientResponse response = client.send(request)
Augmenting the request #
Before you send the request you may want to augment it by adding things such as headers and cookies.
Adding parameters #
HttpClientRequest request = client.createRequest()
request.setParam('foo', 'bar') // Appends the parameters "foo=bar" to the query string.
Setting headers #
HttpClientRequest request = client.createRequest()
request.setHeader('Foo', 'Bar') // This sets the "Foo" header to "Bar"
Setting cookies #
HttpClientRequest request = client.createRequest()
request.setCookie('foo', 'Bar') // This sets a cookie named "foo" whose value is "Bar"
Sending a POST request #
Sending a POST
request involves:
- Creating a request
- Setting its HTTP method to
POST
- Adding data to the request body
- Sending it
The request body can be an instance of
FormData
such as a
UrlEncodedForm
or a
MultiPartForm
(for sending file attachments) or a String
.
Sending a simple form #
Below is an example of how we send some form data. The server will receive this request as an x-www-form-urlencoded
entity.
/* Create the POST request */
HttpClientRequest postRequest = client.createRequest(HttpMethod.POST)
/* Create a form */
FormData formData = FormData.createBasicForm()
formData.setParam('email', 'me@mail.com').setParam('password', 'password1')
// Or alternatively FormData.createBasicForm([email: '...', password: '...'])
/* Add the form to the request body */
postRequest.setBody(formData)
/* Send the request */
client.send(postRequest)
Sending a form with files #
You can also use the HTTP Client to upload files. To do this, you must use a MultipartForm
:
FormData formData = FormData.createMultipartForm()
formData.setParameter('profilePic', new File('profile-pic.jpg'))
postRequest.setBody(formData)
client.send(postRequest)
Sending JSON #
To send a JSON request, pass the JSON string to the HttpClientRequest.setBody()
method and specify a ContentType
:
String json = new SignupForm('me@mail.com', 'password1').toJson()
postRequest.data(json, ContentType.JSON)
client.send(postRequest) // Sent as Content-Type: application/json