A simple HTTP module for easy scripting or interactive use.



get :: String -> IO String

Make an HTTP GET request for the URL given and return the body of the response as a String.

Simple example to print the HTML of a page:

 do html <- get "http://harold.hotelling.net/"
    putStrLn html

Or catch the exceptions with Control.Exception.catch:

 import Control.Exception as E

 do html <- get "http://harold.hotelling.net/" `E.catch` errorHandler
    putStrLn html

Might throw InvalidURLException or HttpException.

post :: Postable a => String -> a -> IO String

Make an HTTP GET request for the URL given sending the list of parameters as if submitting an HTML form and return the body of the response as a String.

You can post anything that is Postable. Several options are pre-defined and the correct Content-Type is used automatically.

  • Strings (sent as text/plain)
  • Form parameters
  • JSON (cabal install json, then import Text.JSON)
  • XML (cabal install xml, then import Text.XML.Light)

For example:

 -- Post url-encoded form inputs: a=1&b=2
 post url [("a", "1"), ("b", "2")]

 -- Post JSON: {"a": 1, "b": 2}
 let json = encJSDict [("a", 1 :: Int), ("b", 2)] in
   post url json

 -- Post XML: <doc><a>1</a><b>2</b></doc>
 case parseXMLDoc "<doc><a>1</a><b>2</b></doc>" of
   Just xml -> post url xml
   Nothing -> ...

You can add support for POSTing any other data type by adding an instance declaration in your code like so:

 instance Postable MyType where
   contentType _ = "some/type"
   serialize value = ...

Might throw InvalidURLException or HttpException.

queryString :: [(String, String)] -> String

A helper function to take a set of parameters and urlencode them so that you can add them to the query string of a URL or the body of a urlencoded POST request.

class Postable a where

Class of types that can be sent via HTTP POST.


contentType :: a -> String

Give the Content-Type header value for this data type.

serialize :: a -> String

Convert the value to a String to send in the body of a POST request.


Postable JSValue 
Postable Element 
Postable [Char] 
Postable [(String, String)] 

data InvalidURLException

This is thrown when a String passed in as a URL fails to parse.

data HttpException

This is thrown when an HTTP request fails, either because of some IO error or because the status code was something other than 200 OK.


Eq HttpException 
Show HttpException 
Typeable HttpException 
Exception HttpException