Pour some sugar on HttpClient
Hey, internet, time has passed and the interface described below has grown, changed, and become its own project: Databinder Dispatch. Most of the snippets in this post won’t compile against today’s Dispatch (don’t worry there are current snippets!) but the spirit is the same so please do read on.
HttpClient: it’s not bad, for a Java library! But how much more fun could it be in Scala, with anonymous functions and methods that look like operators?
val t = new Http("technically.us")
In HttpClient 4, a connection is released automatically when the response body is fully read. That’s nice, but don’t think it will get you out of having a finally
clause. Because you never know! But with Scala you can factor it out by passing a block (after which the response is finally completely read for sure):
(t x new HttpGet("/code")) {
(code, res, entity) => EntityUtils.toString(entity)
}
code
is the response code from the method, res
is the response, and ent
is a response entity. Mostly we want to work with the entity and we only want it if the request was successful, so:
(t x new HttpGet("/code")).when(_ == 200) { EntityUtils.toString(_) }
Or to accept anything 200 to 204:
(t x new HttpGet("/code")) ok { EntityUtils.toString(_) }
Getting sweeter! But why fuss with distinct HTTP method objects for such common cases?
t("/code").as_str
So, those were four different ways to return the web resource as a string. WHat?! Putting the response body into a string makes an application vulnerable to maliciously huge web pages. That is so serious that HttpClient 3 would always log warnings to tell your boss to fire you. This is how you could channel the response to an OutputStream:
t("/code") >>> System.out
Or if you have something that can process an InputStream.
t("/code") >> { do_something_streamy(_) }
Programming is hard—let’s go shopping!
val shiny = Http("http://store.apple.com/1-800-MY-APPLE/WebObjects/AppleStore.woa/wa/RSLID")
shiny << "find" -> "purple shuffle" >>> System.out
The Scala code that brokers this is salty.
Codercomments
hi Nate! i finally figured out that you and Leland might have websites off this technically.us thing!
of course, the cooking one is more interesting and understandable than programming code! but, really, you both are geniuses. i just dig ditches!! love you both, jenn
Aw, come on. You’re the one with the master’s.
The link to the code seems to be broken.
Yes, it is. This is kind of a real project now and it has a permanent home. I’ll add a note to the top of this post.
Thanks for reminding me!
Add a comment