Executing an HTTP GET request
In the previous recipe, Downloading content from the Internet, we described a simple way of getting binary/textual content from a URL. In this recipe, we will present a method to execute HTTP GET
requests with more control over the returned data.
How to do it...
As a starting point, we will use again the same URL
class encountered in the previous recipe. This time we'll explore the openConnection
method of the URL
class in order to have more options for understanding the intricacies of the response returned by the remote server:
We can make the code which retrieves the remote content more reliable by checking the response code as follows:
def url = new URL('http://groovy.codehaus.org/') def connection = url.openConnection() connection.requestMethod = 'GET' if (connection.responseCode == 200) { println connection.content.text println connection.contentType println connection.lastModified connection.headerFields.each { println "> ${it}"} } else { println...