Executing an HTTP POST request
In this recipe, we demonstrate how to POST
data to a remote HTTP server using Groovy. The POST
request method is often used to upload a file or submit a web form to a server. This method sits at the opposite end of the spectrum of the HTTP GET
method, used to retrieve information from the server.
How to do it...
The code required to execute a POST
request with Groovy is fairly similar to the one discussed in the previous recipe, Executing an HTTP GET request, except that it's more convoluted:
The sending of a
POST
request is expressed in the following way:def baseUrl = new URL('http://api.duckduckgo.com') def queryString = 'q=groovy&format=json&pretty=1' def connection = baseUrl.openConnection() connection.with { doOutput = true requestMethod = 'POST' outputStream.withWriter { writer -> writer << queryString } println content.text }
The printed results will look similar to the following code snippet:
{ "Definition" : "groovy...