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:

  1. 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 ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.