Setting Headers on URL Requests with Groovy

The Java URL class can be used to send quick and dirty HTTP requests. In Groovy, it’s especially convenient to quickly get content from the web. This one-liner will fetch the page’s contents:

def webpage = "".toURL().text

Although it’s not well documented, Groovy also provides a convenient way to set headers on the request:

def json = "".toURL().
    getText(requestProperties: [Accept: 'application/json'])

See also: Url.getText(Map parameters)

  1. Mike Miller says:

    Sweet, I know in the past I skipped using that one-liner because I had headers to set. This will come in very handy! Thanks.

  2. JimmyWilk says:

    Thanks! I wish Groovy documented these features better though, I spend a lot of time a’googling for useful posts like this one!

  1. There are no trackbacks for this post yet.