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 = true
      requestMethod = 'POST'
      outputStream.withWriter { writer ->
        writer << queryString
      }
      println content.text
    }
  2. The printed results will look similar to the following code snippet:
    {
       "Definition" :
        "groovy definition: marvelous, wonderful, excellent.",
       "DefinitionSource" : "Merriam-Webster",
       "Heading" : "Groovy",
       "AbstractSource" : "Wikipedia",
       "Image" : "",
       "RelatedTopics" : [
         ...
       ]
       ...
    }

How it works...

The first few lines of the script open a connection to an API provided by the DuckDuckGo search engine, which is an alternative privacy-oriented search service.

To reduce code verbosity we use Groovy's with method, which basically allows us to suppress references to the connection variable and call its methods and properties directly within a closure passed to the Groovy's with method.

Before making a request, we set several connection properties such as requestMethod to indicate that we actually want to fire a POST request. Finally, the code creates a writer object to append to the stream containing the data that will be posted to the remote connection. The response is read by using the text property of the InputStream method returned by the content property (see the Executing an HTTP GET request recipe).

There's more...

Another way to POST data to a web server is to use the HTTPBuilder third-party library (http://groovy.codehaus.org/modules/http-builder/doc/index.html). The project is discussed in more details in the Issuing a REST request and parsing a response recipe.

As we are working with an external dependency, we use Grape to fetch the HTTPBuilder library:

@Grab(
  group='org.codehaus.groovy.modules.http-builder',
  module='http-builder',
  version='0.6'
)
import groovyx.net.http.*

def baseUrl = 'http://api.duckduckgo.com'
def queryString = 'q=groovy&format=json&pretty=1'
def http = new HTTPBuilder(baseUrl)
http.request(Method.POST) {
  send ContentType.URLENC, queryString
  response.success = { response, reader ->
    println response.statusLine
    println reader.text
  }
  response.failure = { response ->
    println response.statusLine
  }
}

The result of the posted data is handled in the response.success closure. We also handle failures (for example, 404 or 500 status codes) in the failure closure. The response variable holds the response metadata such as the status code and the headers. The reader object is used to get access to the remote data stream. Since the reader implements a java.io.Reader interface, we can use the text property provided by Groovy to fully-fetch response content and print it to the standard output.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.18.186