Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Andrey Adamovich - Groovy 2 Cookbook - 2013.pdf
Скачиваний:
44
Добавлен:
19.03.2016
Размер:
26.28 Mб
Скачать

Working with Web Services in Groovy

The code yields the following output:

> http://docs.codehaus.org/pages/editpage.action?spaceKey=GROOVY&title=Pr oject+Information

The code snippet that transforms a Map into a query uses the collect method of the Map. It iterates through the Map entries and executes a simple transformation closure returning a List. The closure simply encodes each parameter value using the java.net.URLEncoder class and adds the = sign between a parameter name and its content. Finally, the join method is applied to the resulting collection to concatenate all entries into a single string using & symbol.

See also

ff Downloading content from the Internet

ff Constructing and modifying complex URLs ff Executing an HTTP POST request

ff http://docs.oracle.com/javase/6/docs/api/java/net/ URLConnection.html

ff http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder. html

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'

268

www.it-ebooks.info

Chapter 8

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.

269

www.it-ebooks.info

Working with Web Services in Groovy

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

ff http://groovy.codehaus.org/modules/http-builder

ff The Simplifying dependency management with Grape recipe in Chapter 2, Using Groovy Ecosystem

ff ff

Constructing and modifying complex URLs Executing an HTTP GET request

270

www.it-ebooks.info

Chapter 8

Constructing and modifying complex URLs

At the heart of any HTTP request, there is a Universal Resource Locator (URL) or a more generic Universal Resource Identifier (URI) which identifies the target of the operation we need to perform.

We have seen in the previous recipes (for example, the Downloading content from the Internet recipe) that it's very hard to avoid dealing with URLs when interacting with the HTTP protocol. In this recipe, we are going to present a more structured approach to constructing and modifying complex URLs with the help of an additional Groovy library.

How to do it...

If you have worked with Java's URL class before, you know that the only way to construct instances of that class is to provide a full URL to the constructor, which will return an immutable (non-changeable) object.

Groovy's core does not add any special support for URL manipulation apart from what Java already offers, but there is an officially supported HttpBuilder module that is hosted on Groovy's website (http://groovy.codehaus.org/modules/http-builder) and that can be used to make more accessible URL creation and modification:

1.First of all, we need to @Grab that module and import the URIBuilder class, which will help us with our task:

@Grab( group='org.codehaus.groovy.modules.http-builder', module='http-builder',

version='0.6'

)

import groovyx.net.http.URIBuilder

2.At this point, we can create a URIBuilder instance and pass baseUri to that:

def baseUri = 'http://groovy.services.com/service1/operation2'

def uri = new URIBuilder(baseUri)

3.Now, we can modify any URI's component with simple property assignments, as follows:

uri.with {

scheme = 'https' host = 'localhost' port = 8080

271

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]