EZHTTP
Description
A simple HTTP module for easy scripting or interactive use.
- get :: String -> IO String
- post :: Postable a => String -> a -> IO String
- queryString :: [(String, String)] -> String
- class Postable a where
- contentType :: a -> String
- serialize :: a -> String
- data InvalidURLException
- data HttpException
Documentation
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.
Methods
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.
data InvalidURLException
This is thrown when a String passed in as a URL fails to parse.
Instances
Eq InvalidURLException | |
Show InvalidURLException | |
Typeable InvalidURLException | |
Exception InvalidURLException |
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.
Instances
Eq HttpException | |
Show HttpException | |
Typeable HttpException | |
Exception HttpException |