Tuesday, November 27, 2007

Web requests with the Haskell HTTP library

Overview

Web development work can exist at the server level but it can also exist at the client level. You may need to build a simple HTTP load test framework or test if a particular web application or page is available. It is also possible that you need to upload files. I have built a couple of simple HTTP frameworks in Java and Python but this be a first attempt at Haskell based framework. Actually, in this small example; there isn't much of a framework but just an example on how to use the most recent HTTP library update.

Install the HTTP library

It seems that GHC Haskell release 6.8 encourages that libraries exist outside of the base Haskell build. For example, the parsec parser library requires that you download parsec from haskell.org or other location or extract the source from darcs. Basically, development will continue on haskell libraries outside of the typical GHC development. With that being said, the same holds true for the HTTP library. You can pull the source from darcs or at the time of this blog entry, the latest HTTP library is HTTP-3001.0.2. I downloaded and did a Setup.hs configure/build/install against GHC version 6.8.

If you attempted to compile haskell source with out installing this library, you will get a package not found error.

ghc --make -package HTTP ManClient.hs

What does and do and how

The goal of this simple application is to post data or actually could be used to post to any website. Also, if you simply replace the POST string type in the code to GET, you can use this code to read content from a website and print the web page to the console.
Get Function

get :: URI -> IO String
get uri =
do
eresp <- simpleHTTPProxy (manRequest uri)
resp <- handleErr (err . show) eresp
case rspCode resp of
(2,0,0) -> return (rspBody resp)
_ -> err (httpError resp)
where
showRspCode (a,b,c) = map intToDigit [a,b,c]
httpError resp =
showRspCode (rspCode resp) ++ " " ++ rspReason resp

Build the Request Type


manRequest :: URI -> Request
manRequest uri = Request { rqURI = uri,
rqMethod = POST,
rqHeaders = [
Header HdrContentLength
(show (length forumRequestBody)),
Header HdrUserAgent userAgentMimicIE
],
rqBody = forumRequestBody }

Download Source

http://haskellnotebook.googlecode.com/svn/trunk/haskell/laughingman/haskell/ManClient.hs


No comments: