Posts Tagged ‘java’

Setting Headers on URL Requests with Groovy

Posted in Code on February 6th, 2014 by ataylor284 – 2 Comments

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 = "http://www.example.com/someUrl".toURL().text

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

def json = "http://www.example.com/api/myresouce".toURL().
    getText(requestProperties: [Accept: 'application/json'])

See also: Url.getText(Map parameters)

Guess the Content-type from Filename

Posted in Code on January 17th, 2012 by ataylor284 – Comments Off on Guess the Content-type from Filename

Java has a helpful little function for guessing the content-type based on the file name:

URLConnection.getFileNameMap().getContentTypeFor(filename)

You can check out — or customize — the mappings which are stored in $JRE_HOME/lib/content-types.properties.

So if you’re serving up a file and you’re not quite sure what content-type to use, let Java take a guess.