Downloading content from the Internet
The title of this recipe may not seem related to web services at a first glance, but since most of the available services are actually based on Hyper Text Transfer Protocol (HTTP) as well as most of the content on the Internet, it is worth starting with getting a basic understanding of simple HTTP operations before diving into the more complex world of web services.
How to do it...
For downloading HTTP-based content, we don't need any special libraries or stratagem. All that is needed are the standard Java classes—File
and URL
—and their Groovy extensions:
We first start with defining our target and source files:
def outputFile = new File('image.png') def baseUrl = 'http://groovy.codehaus.org' def imagePath = '/images/groovy-logo-medium.png' def url = new URL("${baseUrl}${imagePath}")
Then, just in case, the
outputFile
already exists, we need to delete it to avoid appending content:outputFile.delete()
The last step is to stream the URL's content into the
outputFile...