Databinder Dispatch for HTTP services
I do like Databinder Dispatch. It wrappers HttpClient and adds in support for oAuth, Twitter and other web services, letting you write code like this:
import dispatch._
import Http._
val http = new Http
http("http://databinder.net/dispatch/Stdout_Walkthrough" >>>
System.out)
I admit it might seem a little odd the first time you dig in to use it. What I found useful was looking at the source which has been formatted with Scala X-Rays—itself quite a eye opener, giving something as useful as an IDE in a browser without actually having an IDE in a browser.
What's happening with the http(...) call is a HttpClient is being invoked via a Handler. That is, the parameter to the http() call needs to be a Handler, and a Handler is something that takes a request and... handles it, by making use of what comes back from the request, for example.
How do you get a Handler? You can write your own, but another way is to take a Requestand call a method on the Request to give you a Handler. In the above example the String "http://databinder..." is converted to a Request via an implicit in scope as a result of the import. The >>> method on the Request gives you a Handler. In this case, it's a Handler that writes the response to the given stream.
As you might imagine there are lots of methods to give you all sorts of different Handlers, and these can be chained in various ways to set headers, perform POSTs, set encodings.... there's quite a list in Http.scala.
You need to do asynchronous HTTP? It's there. Dealing in Json? Yup, that's there too. An impressive library.
Aside:
If you want to just grab some content, work with the content, and return something you could write:
def withContentFrom[T](url: String)(f: String => T): T = new Http().apply(new Request(url) >- f)
val result = withContentFrom("http://whatever.example.com") {
html => // do you thing with html
}
Handy for scripting.