Posts Tagged ‘http’

Setting Headers on URL Requests with Groovy

Posted in Code on February 6th, 2014 by ataylor284 – 1 Comment

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)

Logging HttpBuilder traffic

Posted in Code on October 18th, 2013 by ataylor284 – Be the first to comment

Groovy and HttpBuilder are a nice way to write quick scripts to exercise web services. It’s especially useful when it’s just a bit too complex for something like curl. Unfortunately, there’s no quick way to trace all the I/O as with curl’s –trace, but turning on logging isn’t too difficult.

HttpBuilder uses HttpClient, which does some logging with Apache’s commons-logging. Without any additional libraries or configuration, it will fall back on Java’s java.util.logging package. Java expects it’s logging configuration in a properties file. Here’s a minimal config:

handlers=java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level=FINEST
.level=FINEST
httpclient.wire.header.level=FINEST
org.apache.commons.httpclient.level=FINEST

Launch groovy with the right system property, and all the output will be logged.

groovy -Djava.util.logging.config.file=logging.properties \
  MyHttpBuilderScript.groovy

Simple Servlets in Groovy

Posted in Code on February 29th, 2012 by ataylor284 – 12 Comments

A feature I miss in groovy is a simple way to create a self-contained web server without a web container like Tomcat. Python, in particular, has a nice solution for this with its HTTPServer class. It’s not something to write a full application with, but it’s an extremely convenient tool to have available.

The best solution I’ve found is Jetty, the embedded Java web server. It has a nice simple interface and runs any Servlet right out of your script:

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*

def runWithJetty(servlet, port) {
   def jetty = new Server(port)
   def context = new Context(jetty, '/', Context.SESSIONS)
   context.addServlet(new ServletHolder(servlet), '/*')
   jetty.start()
}

Groovy has groovlets and GroovyServlet, a nice little wrapper for writing Servlets. However, it requires you to structure your project in a specific way: each Servlet in a separate file, mapped to URI paths by file name.

By hooking up ServletCategory and ServletBinding to a closure, it’s possible to get the nice features of groovlets without the GroovyServlet limitations:

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*
import javax.servlet.http.*
import javax.servlet.ServletConfig

class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        super.init(config)
        context = config.servletContext
    }
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
            requestHandler.call()
        }
    }
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')
        jetty.start()
    }
}

Combined with the above, a simple self-contained web server becomes as clean and concise as groovy should be:

SimpleGroovyServlet.run(8080) { ->
    response.contentType = 'text/plain'
    println "hello world!"
    println "my path is ${request.pathInfo}"
    println "my params are $params"
}

Guess the Content-type from Filename

Posted in Code on January 17th, 2012 by ataylor284 – Be the first to comment

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.