-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A library for client-side HTTP -- -- A package for sending and receiving HTTP requests and responses, all -- implemented in Haskell (assuming you've already got a network stack to -- spare, via the network package!) The representation of content -- of in requests and responses is user-controllable, letting you pick a -- representation that fits your code better (e.g., use -- ByteStrings rather than the default Haskell -- Strings.) Example uses: -- --
--   do
--     rsp <- Network.HTTP.simpleHTTP (getRequest "http://www.haskell.org/")
--             -- fetch document and return it (as a 'String'.)
--     fmap (take 100) (getResponseBody rsp)
--   
--   do
--     rsp <- Network.Browser.browse $ do
--              setAllowRedirects True -- handle HTTP redirects
--              request $ getRequest "http://google.com/"
--     fmap (take 100) (getResponseBody rsp)
--   
-- -- Git repository available at git://code.galois.com/HTTPbis.git @package HTTP @version 4000.0.7 -- | An library for creating abstract streams. Originally part of -- Gray's\/Bringert's HTTP module. -- -- module Network.Stream -- | Streams should make layering of TLS protocol easier in future, they -- allow reading/writing to files etc for debugging, they allow use of -- protocols other than TCP/IP and they allow customisation. -- -- Instances of this class should not trim the input in any way, e.g. -- leave LF on line endings etc. Unless that is exactly the behaviour you -- want from your twisted instances ;) class Stream x readLine :: (Stream x) => x -> IO (Result String) readBlock :: (Stream x) => x -> Int -> IO (Result String) writeBlock :: (Stream x) => x -> String -> IO (Result ()) close :: (Stream x) => x -> IO () data ConnError ErrorReset :: ConnError ErrorClosed :: ConnError ErrorParse :: String -> ConnError ErrorMisc :: String -> ConnError -- | This is the type returned by many exported network functions. type Result a = Either ConnError a bindE :: Result a -> (a -> Result b) -> Result b fmapE :: (a -> Result b) -> IO (Result a) -> IO (Result b) failParse :: String -> Result a failWith :: ConnError -> Result a instance Show ConnError instance Eq ConnError instance Error ConnError -- | This module provides the data types for representing HTTP headers, and -- operations for looking up header values and working with sequences of -- header values in Requests and Responses. To avoid -- having to provide separate set of operations for doing so, we -- introduce a type class HasHeaders to facilitate writing such -- processing using overloading instead. module Network.HTTP.Headers -- | HasHeaders is a type class for types containing HTTP headers, -- allowing you to write overloaded header manipulation functions for -- both Request and Response data types, for instance. class HasHeaders x getHeaders :: (HasHeaders x) => x -> [Header] setHeaders :: (HasHeaders x) => x -> [Header] -> x -- | The Header data type pairs header names & values. data Header Header :: HeaderName -> String -> Header -- | Header constructor as a function, hiding above rep. mkHeader :: HeaderName -> String -> Header hdrName :: Header -> HeaderName hdrValue :: Header -> String -- | HTTP HeaderName type, a Haskell data constructor for each -- specification-defined header, prefixed with Hdr and -- CamelCased, (i.e., eliding the - in the process.) Should you -- require using a custom header, there's the HdrCustom -- constructor which takes a String argument. -- -- Encoding HTTP header names differently, as Strings perhaps, is an -- equally fine choice..no decidedly clear winner, but let's stick with -- data constructors here. data HeaderName HdrCacheControl :: HeaderName HdrConnection :: HeaderName HdrDate :: HeaderName HdrPragma :: HeaderName HdrTransferEncoding :: HeaderName HdrUpgrade :: HeaderName HdrVia :: HeaderName HdrAccept :: HeaderName HdrAcceptCharset :: HeaderName HdrAcceptEncoding :: HeaderName HdrAcceptLanguage :: HeaderName HdrAuthorization :: HeaderName HdrCookie :: HeaderName HdrExpect :: HeaderName HdrFrom :: HeaderName HdrHost :: HeaderName HdrIfModifiedSince :: HeaderName HdrIfMatch :: HeaderName HdrIfNoneMatch :: HeaderName HdrIfRange :: HeaderName HdrIfUnmodifiedSince :: HeaderName HdrMaxForwards :: HeaderName HdrProxyAuthorization :: HeaderName HdrRange :: HeaderName HdrReferer :: HeaderName HdrUserAgent :: HeaderName HdrAge :: HeaderName HdrLocation :: HeaderName HdrProxyAuthenticate :: HeaderName HdrPublic :: HeaderName HdrRetryAfter :: HeaderName HdrServer :: HeaderName HdrSetCookie :: HeaderName HdrTE :: HeaderName HdrTrailer :: HeaderName HdrVary :: HeaderName HdrWarning :: HeaderName HdrWWWAuthenticate :: HeaderName HdrAllow :: HeaderName HdrContentBase :: HeaderName HdrContentEncoding :: HeaderName HdrContentLanguage :: HeaderName HdrContentLength :: HeaderName HdrContentLocation :: HeaderName HdrContentMD5 :: HeaderName HdrContentRange :: HeaderName HdrContentType :: HeaderName HdrETag :: HeaderName HdrExpires :: HeaderName HdrLastModified :: HeaderName -- | MIME entity headers (for sub-parts) HdrContentTransferEncoding :: HeaderName -- | Allows for unrecognised or experimental headers. HdrCustom :: String -> HeaderName -- | insertHeader hdr val x inserts a header with the given header -- name and value. Does not check for existing headers with same name, -- allowing duplicates to be introduce (use replaceHeader if you -- want to avoid this.) insertHeader :: (HasHeaders a) => HeaderSetter a -- | insertHeaderIfMissing hdr val x adds the new header only if -- no previous header with name hdr exists in x. insertHeaderIfMissing :: (HasHeaders a) => HeaderSetter a -- | insertHeaders hdrs x appends multiple headers to x's -- existing set. insertHeaders :: (HasHeaders a) => [Header] -> a -> a -- | retrieveHeaders hdrNm x gets a list of headers with -- HeaderName hdrNm. retrieveHeaders :: (HasHeaders a) => HeaderName -> a -> [Header] -- | replaceHeader hdr val o replaces the header hdr with -- the value val, dropping any existing replaceHeader :: (HasHeaders a) => HeaderSetter a -- | findHeader hdrNm x looks up hdrNm in x, -- returning the first header that matches, if any. findHeader :: (HasHeaders a) => HeaderName -> a -> Maybe String -- | lookupHeader hdr hdrs locates the first header matching -- hdr in the list hdrs. lookupHeader :: HeaderName -> [Header] -> Maybe String -- | parseHeader headerNameAndValueString tries to unscramble a -- header: value pairing and returning it as a Header. parseHeader :: String -> Result Header -- | parseHeaders hdrs takes a sequence of strings holding header -- information and parses them into a set of headers (preserving their -- order in the input argument.) Handles header values split up over -- multiple lines. parseHeaders :: [String] -> Result [Header] type HeaderSetter a = HeaderName -> String -> a -> a instance Eq HeaderName instance Show HeaderName instance Show Header -- | In order to give the user freedom in how request and response content -- is represented, a sufficiently abstract representation is needed of -- these internally. The Network.BufferType module provides this, -- defining the BufferType class and its ad-hoc representation of -- buffer operations via the BufferOp record. -- -- This module provides definitions for the standard buffer types that -- the package supports, i.e., for String and -- ByteString (strict and lazy.) module Network.BufferType -- | The BufferType class encodes, in a mixed-mode way, the -- interface that the library requires to operate over data embedded in -- HTTP requests and responses. That is, we use explicit dictionaries for -- the operations, but overload the name of the dicts themselves. class BufferType bufType bufferOps :: (BufferType bufType) => BufferOp bufType -- | BufferOp encodes the I/O operations of the underlying buffer -- over a Handle in an (explicit) dictionary type. May not be needed, but -- gives us flexibility in explicit overriding and wrapping up of these -- methods. -- -- Along with IO operations is an ad-hoc collection of functions for -- working with these abstract buffers, as needed by the internals of the -- code that processes requests and responses. -- -- We supply three default BufferOp values, for String -- along with the strict and lazy versions of ByteString. To add -- others, provide BufferOp definitions for data BufferOp a BufferOp :: (Handle -> Int -> IO a) -> (Handle -> IO a) -> (Handle -> a -> IO ()) -> (Handle -> IO a) -> a -> (a -> a -> a) -> ([a] -> a) -> (String -> a) -> (a -> String) -> (a -> Word8 -> a) -> (Int -> a -> (a, a)) -> ((Char -> Bool) -> a -> (a, a)) -> (a -> Bool) -> (a -> Bool) -> BufferOp a buf_hGet :: BufferOp a -> Handle -> Int -> IO a buf_hGetContents :: BufferOp a -> Handle -> IO a buf_hPut :: BufferOp a -> Handle -> a -> IO () buf_hGetLine :: BufferOp a -> Handle -> IO a buf_empty :: BufferOp a -> a buf_append :: BufferOp a -> a -> a -> a buf_concat :: BufferOp a -> [a] -> a buf_fromStr :: BufferOp a -> String -> a buf_toStr :: BufferOp a -> a -> String buf_snoc :: BufferOp a -> a -> Word8 -> a buf_splitAt :: BufferOp a -> Int -> a -> (a, a) buf_span :: BufferOp a -> (Char -> Bool) -> a -> (a, a) buf_isLineTerm :: BufferOp a -> a -> Bool buf_isEmpty :: BufferOp a -> a -> Bool -- | strictBufferOp is the BufferOp definition over -- ByteStrings, the non-lazy kind. strictBufferOp :: BufferOp ByteString -- | lazyBufferOp is the BufferOp definition over -- ByteStrings, the non-strict kind. lazyBufferOp :: BufferOp ByteString -- | stringBufferOp is the BufferOp definition over -- Strings. It is defined in terms of strictBufferOp -- operations, unpacking/converting to String when needed. stringBufferOp :: BufferOp String instance Eq (BufferOp a) instance BufferType String instance BufferType ByteString instance BufferType ByteString -- | Definitions of Request and Response types along with -- functions for normalizing them. It is assumed to be an internal -- module; user code should, if possible, import Network.HTTP to -- access the functionality that this module provides. -- -- Additionally, the module exports internal functions for working with -- URLs, and for handling the processing of requests and responses coming -- back. module Network.HTTP.Base httpVersion :: String -- | An HTTP Request. The Show instance of this type is used for -- message serialisation, which means no body data is output. data Request a Request :: URI -> RequestMethod -> [Header] -> a -> Request a -- | might need changing in future 1) to support * uri in OPTIONS -- request 2) transparent support for both relative & absolute uris, -- although this should already work (leave scheme & host parts -- empty). rqURI :: Request a -> URI rqMethod :: Request a -> RequestMethod rqHeaders :: Request a -> [Header] rqBody :: Request a -> a -- | An HTTP Response. The Show instance of this type is used for -- message serialisation, which means no body data is output, -- additionally the output will show an HTTP version of 1.1 instead of -- the actual version returned by a server. data Response a Response :: ResponseCode -> String -> [Header] -> a -> Response a rspCode :: Response a -> ResponseCode rspReason :: Response a -> String rspHeaders :: Response a -> [Header] rspBody :: Response a -> a -- | The HTTP request method, to be used in the Request object. We -- are missing a few of the stranger methods, but these are not really -- necessary until we add full TLS. data RequestMethod HEAD :: RequestMethod PUT :: RequestMethod GET :: RequestMethod POST :: RequestMethod DELETE :: RequestMethod OPTIONS :: RequestMethod TRACE :: RequestMethod CONNECT :: RequestMethod Custom :: String -> RequestMethod type Request_String = Request String type Response_String = Response String type HTTPRequest a = Request a type HTTPResponse a = Response a urlEncode :: String -> String urlDecode :: String -> String urlEncodeVars :: [(String, String)] -> String data URIAuthority URIAuthority :: Maybe String -> Maybe String -> String -> Maybe Int -> URIAuthority user :: URIAuthority -> Maybe String password :: URIAuthority -> Maybe String host :: URIAuthority -> String port :: URIAuthority -> Maybe Int -- | Parse the authority part of a URL. -- --
--   RFC 1732, section 3.1:
--   
--         //<user>:<password>@<host>:<port>/<url-path>
--    Some or all of the parts "<user>:<password>@", ":<password>",
--    ":<port>", and "/<url-path>" may be excluded.
--   
parseURIAuthority :: String -> Maybe URIAuthority uriToAuthorityString :: URI -> String uriAuthToString :: URIAuth -> String uriAuthPort :: Maybe URI -> URIAuth -> Int reqURIAuth :: Request ty -> URIAuth parseResponseHead :: [String] -> Result ResponseData parseRequestHead :: [String] -> Result RequestData data ResponseNextStep Continue :: ResponseNextStep Retry :: ResponseNextStep Done :: ResponseNextStep ExpectEntity :: ResponseNextStep DieHorribly :: String -> ResponseNextStep matchResponse :: RequestMethod -> ResponseCode -> ResponseNextStep -- | ResponseData contains the head of a response payload; HTTP -- response code, accompanying text description + header fields. type ResponseData = (ResponseCode, String, [Header]) -- | For easy pattern matching, HTTP response codes xyz are -- represented as (x,y,z). type ResponseCode = (Int, Int, Int) -- | RequestData contains the head of a HTTP request; method, its -- URL along with the auxillary/supporting header data. type RequestData = (RequestMethod, URI, [Header]) -- | NormalizeRequestOptions brings together the various -- defaulting/normalization options over Requests. Use -- defaultNormalizeRequestOptions for the standard selection of -- option data NormalizeRequestOptions ty NormalizeRequestOptions :: Bool -> Bool -> Maybe String -> [RequestNormalizer ty] -> NormalizeRequestOptions ty normDoClose :: NormalizeRequestOptions ty -> Bool normForProxy :: NormalizeRequestOptions ty -> Bool normUserAgent :: NormalizeRequestOptions ty -> Maybe String normCustoms :: NormalizeRequestOptions ty -> [RequestNormalizer ty] defaultNormalizeRequestOptions :: NormalizeRequestOptions ty -- | RequestNormalizer is the shape of a (pure) function that -- rewrites a request into some normalized form. type RequestNormalizer ty = NormalizeRequestOptions ty -> Request ty -> Request ty -- | normalizeRequest opts req is the entry point to use to -- normalize your request prior to transmission (or other use.) -- Normalization is controlled via the NormalizeRequestOptions -- record. normalizeRequest :: NormalizeRequestOptions ty -> Request ty -> Request ty splitRequestURI :: URI -> (String, URI) -- | getAuth req fishes out the authority portion of the URL in a -- request's Host header. getAuth :: (Monad m) => Request ty -> m URIAuthority normalizeRequestURI :: Bool -> String -> Request ty -> Request ty normalizeHostHeader :: Request ty -> Request ty findConnClose :: [Header] -> Bool -- | Used when we know exactly how many bytes to expect. linearTransfer :: (Int -> IO (Result a)) -> Int -> IO (Result ([Header], a)) -- | Used when nothing about data is known, Unfortunately waiting for a -- socket closure causes bad behaviour. Here we just take data once and -- give up the rest. hopefulTransfer :: BufferOp a -> IO (Result a) -> [a] -> IO (Result ([Header], a)) -- | A necessary feature of HTTP/1.1 Also the only transfer variety likely -- to return any footers. chunkedTransfer :: BufferOp a -> IO (Result a) -> (Int -> IO (Result a)) -> IO (Result ([Header], a)) -- | Maybe in the future we will have a sensible thing to do here, at that -- time we might want to change the name. uglyDeathTransfer :: String -> IO (Result ([Header], a)) -- | Remove leading crlfs then call readTillEmpty2 (not required by RFC) readTillEmpty1 :: BufferOp a -> IO (Result a) -> IO (Result [a]) -- | Read lines until an empty line (CRLF), also accepts a connection close -- as end of input, which is not an HTTP/1.1 compliant thing to do - so -- probably indicates an error condition. readTillEmpty2 :: BufferOp a -> IO (Result a) -> [a] -> IO (Result [a]) defaultGETRequest :: URI -> Request_String defaultGETRequest_ :: (BufferType a) => URI -> Request a -- | 'mkRequest method uri' constructs a well formed request for the given -- HTTP method and URI. It does not normalize the URI for the request -- _nor_ add the required Host: header. That is done either explicitly by -- the user or when requests are normalized prior to transmission. mkRequest :: (BufferType ty) => RequestMethod -> URI -> Request ty defaultUserAgent :: String libUA :: String -- | catchIO a h handles IO action exceptions throughout codebase; -- version-specific tweaks better go here. catchIO :: IO a -> (IOException -> IO a) -> IO a catchIO_ :: IO a -> IO a -> IO a responseParseError :: String -> String -> Result a -- | getRequestVersion req returns the HTTP protocol version of -- the request req. If Nothing, the default -- httpVersion can be assumed. getRequestVersion :: Request a -> Maybe String -- | getResponseVersion rsp returns the HTTP protocol version of -- the response rsp. If Nothing, the default -- httpVersion can be assumed. getResponseVersion :: Response a -> Maybe String -- | setRequestVersion v req returns a new request, identical to -- req, but with its HTTP version set to v. setRequestVersion :: String -> Request a -> Request a -- | setResponseVersion v rsp returns a new response, identical to -- rsp, but with its HTTP version set to v. setResponseVersion :: String -> Response a -> Response a instance Eq RequestMethod instance Eq URIAuthority instance Show URIAuthority instance HasHeaders (Response a) instance Show (Response a) instance HasHeaders (Request a) instance Show (Request a) instance Show RequestMethod -- | Some utility functions for working with the Haskell network -- package. Mostly for internal use by the Network.HTTP code, -- but module Network.TCP -- | The Connection newtype is a wrapper that allows us to make -- connections an instance of the Stream class, without GHC extensions. -- While this looks sort of like a generic reference to the transport -- layer it is actually TCP specific, which can be seen in the -- implementation of the 'Stream Connection' instance. data Connection -- | openTCPPort uri port establishes a connection to a remote -- host, using getHostByName which possibly queries the DNS -- system, hence may trigger a network connection. openTCPPort :: String -> Int -> IO Connection -- | Checks both that the underlying Socket is connected and that the -- connection peer matches the given host name (which is recorded -- locally). isConnectedTo :: Connection -> String -> IO Bool openTCPConnection :: (BufferType ty) => String -> Int -> IO (HandleStream ty) -- | socketConnection, like openConnection but using a -- pre-existing Socket. socketConnection :: (BufferType ty) => String -> Socket -> IO (HandleStream ty) isTCPConnectedTo :: HandleStream ty -> String -> IO Bool data HandleStream a -- | HStream overloads the use of HandleStreams, letting -- you overload the handle operations over the type that is communicated -- across the handle. It is used in the context of Network.HTTP -- to buy us freedom in how HTTP Request and Response -- payloads are represented. -- -- The package provides instances for ByteStrings and -- String, but should you want to plug in your own payload -- representation, defining your own HStream instance is all it -- takes. class (BufferType bufType) => HStream bufType openStream :: (HStream bufType) => String -> Int -> IO (HandleStream bufType) openSocketStream :: (HStream bufType) => String -> Socket -> IO (HandleStream bufType) readLine :: (HStream bufType) => HandleStream bufType -> IO (Result bufType) readBlock :: (HStream bufType) => HandleStream bufType -> Int -> IO (Result bufType) writeBlock :: (HStream bufType) => HandleStream bufType -> bufType -> IO (Result ()) close :: (HStream bufType) => HandleStream bufType -> IO () data StreamHooks ty StreamHooks :: ((ty -> String) -> Result ty -> IO ()) -> ((ty -> String) -> Int -> Result ty -> IO ()) -> ((ty -> String) -> ty -> Result () -> IO ()) -> IO () -> StreamHooks ty hook_readLine :: StreamHooks ty -> (ty -> String) -> Result ty -> IO () hook_readBlock :: StreamHooks ty -> (ty -> String) -> Int -> Result ty -> IO () hook_writeBlock :: StreamHooks ty -> (ty -> String) -> ty -> Result () -> IO () hook_close :: StreamHooks ty -> IO () nullHooks :: StreamHooks ty setStreamHooks :: HandleStream ty -> StreamHooks ty -> IO () hstreamToConnection :: HandleStream String -> Connection instance (Eq a) => Eq (Conn a) instance HStream String instance Stream Connection instance HStream ByteString instance HStream ByteString instance (Eq ty) => Eq (StreamHooks ty) -- | Implements debugging of Streams. Originally part of -- Gray's\/Bringert's HTTP module. -- -- module Network.StreamDebugger -- | Allows stream logging. Refer to debugStream below. data StreamDebugger x -- | Wraps a stream with logging I/O. The first argument is a filename -- which is opened in AppendMode. debugStream :: (Stream a) => FilePath -> a -> IO (StreamDebugger a) debugByteStream :: (HStream ty) => FilePath -> HandleStream ty -> IO (HandleStream ty) instance (Stream x) => Stream (StreamDebugger x) -- | Socket Stream instance. Originally part of Gray's\/Bringert's HTTP -- module. -- -- module Network.StreamSocket -- | Exception handler for socket operations. handleSocketError :: Socket -> IOException -> IO (Result a) myrecv :: Socket -> Int -> IO String instance Stream Socket -- | A HandleStream-based version of Network.HTTP interface. -- -- For more detailed information about what the individual exports do, -- please consult the documentation for Network.HTTP. -- Notice however that the functions here do not perform any kind -- of normalization prior to transmission (or receipt); you are -- responsible for doing any such yourself, or, if you prefer, just -- switch to using Network.HTTP function instead. module Network.HTTP.HandleStream -- | simpleHTTP transmits a resource across a non-persistent -- connection. simpleHTTP :: (HStream ty) => Request ty -> IO (Result (Response ty)) -- | Like simpleHTTP, but acting on an already opened stream. simpleHTTP_ :: (HStream ty) => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP hStream httpRequest transmits httpRequest -- over hStream, but does not alter the status of the -- connection, nor request it to be closed upon receiving the response. sendHTTP :: (HStream ty) => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP_notify hStream httpRequest action behaves like -- sendHTTP, but lets you supply an IO action to execute -- once the request has been successfully transmitted over the -- connection. Useful when you want to set up tracing of request -- transmission and its performance. sendHTTP_notify :: (HStream ty) => HandleStream ty -> Request ty -> IO () -> IO (Result (Response ty)) -- | receiveHTTP hStream reads a Request from the -- HandleStream hStream receiveHTTP :: (HStream bufTy) => HandleStream bufTy -> IO (Result (Request bufTy)) -- | respondHTTP hStream httpResponse transmits an HTTP -- Response over the HandleStream hStream. It -- could be used to implement simple web server interactions, performing -- the dual role to sendHTTP. respondHTTP :: (HStream ty) => HandleStream ty -> Response ty -> IO () -- | simpleHTTP_debug debugFile req behaves like -- simpleHTTP, but logs the HTTP operation via the debug file -- debugFile. simpleHTTP_debug :: (HStream ty) => FilePath -> Request ty -> IO (Result (Response ty)) -- | The Network.HTTP module provides a simple interface for -- sending and receiving content over HTTP in Haskell. Here's how to -- fetch a document from a URL and return it as a String: -- --
--   simpleHTTP (getRequest "http://www.haskell.org/") >>= fmap (take 100) . getResponseBody
--       -- fetch document and return it (as a 'String'.)
--   
-- -- Other functions let you control the submission and transfer of HTTP -- Requests and Responses more carefully, letting you -- integrate the use of Network.HTTP functionality into your -- application. -- -- The module also exports the main types of the package, Request -- and Response, along with Header and functions for -- working with these. -- -- The actual functionality is implemented by modules in the -- Network.HTTP.* namespace, letting you either use the default -- implementation here by importing Network.HTTP or, for more -- specific uses, selectively import the modules in -- Network.HTTP.*. To wit, more than one kind of representation -- of the bulk data that flows across a HTTP connection is supported. -- (see Network.HTTP.HandleStream.) -- -- NOTE: The Request send actions will normalize the -- Request prior to transmission. Normalization such as having -- the request path be in the expected form and, possibly, introduce a -- default Host: header if one isn't already present. If you do -- not want the requests tampered with, but sent as-is, please import and -- use the the Network.HTTP.HandleStream or -- Network.HTTP.Stream modules instead. They export the same -- functions, but leaves construction and any normalization of -- Requests to the user. module Network.HTTP -- | simpleHTTP req transmits the Request req by -- opening a direct, non-persistent connection to the HTTP server -- that req is destined for, followed by transmitting it and -- gathering up the response as a Result. Prior to sending the -- request, it is normalized (via normalizeRequest). If you have -- to mediate the request via an HTTP proxy, you will have to normalize -- the request yourself. Or switch to using Network.Browser -- instead. -- -- Examples: -- --
--   simpleHTTP (getRequest "http://hackage.haskell.org/")
--   simpleHTTP (getRequest "http://hackage.haskell.org:8012/")
--   
simpleHTTP :: (HStream ty) => Request ty -> IO (Result (Response ty)) -- | Identical to simpleHTTP, but acting on an already opened -- stream. simpleHTTP_ :: (HStream ty) => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP hStream httpRequest transmits httpRequest -- (after normalization) over hStream, but does not alter the -- status of the connection, nor request it to be closed upon receiving -- the response. sendHTTP :: (HStream ty) => HandleStream ty -> Request ty -> IO (Result (Response ty)) -- | sendHTTP_notify hStream httpRequest action behaves like -- sendHTTP, but lets you supply an IO action to execute -- once the request has been successfully transmitted over the -- connection. Useful when you want to set up tracing of request -- transmission and its performance. sendHTTP_notify :: (HStream ty) => HandleStream ty -> Request ty -> IO () -> IO (Result (Response ty)) -- | receiveHTTP hStream reads a Request from the -- HandleStream hStream receiveHTTP :: (HStream ty) => HandleStream ty -> IO (Result (Request ty)) -- | respondHTTP hStream httpResponse transmits an HTTP -- Response over the HandleStream hStream. It -- could be used to implement simple web server interactions, performing -- the dual role to sendHTTP. respondHTTP :: (HStream ty) => HandleStream ty -> Response ty -> IO () -- | getRequest urlString is convenience constructor for basic GET -- Requests. If urlString isn't a syntactically valid -- URL, the function raises an error. getRequest :: String -> Request_String -- | postRequest urlString is convenience constructor for POST -- Requests. If urlString isn't a syntactically valid -- URL, the function raises an error. postRequest :: String -> Request_String -- | getResponseBody response takes the response of a HTTP -- requesting action and tries to extricate the body of the -- Response response. If the request action returned an -- error, an IO exception is raised. getResponseBody :: Result (Response ty) -> IO ty -- | Transmitting HTTP requests and responses holding String in -- their payload bodies. This is one of the implementation modules for -- the Network.HTTP interface, representing request and response -- content as Strings and transmitting them in non-packed form -- (cf. Network.HTTP.HandleStream and its use of -- ByteStrings.) over Stream handles. It is mostly here -- for backwards compatibility, representing how requests and responses -- were transmitted up until the 4.x releases of the HTTP package. -- -- For more detailed information about what the individual exports do, -- please consult the documentation for Network.HTTP. -- Notice however that the functions here do not perform any kind -- of normalization prior to transmission (or receipt); you are -- responsible for doing any such yourself, or, if you prefer, just -- switch to using Network.HTTP function instead. module Network.HTTP.Stream -- | Simple way to transmit a resource across a non-persistent connection. simpleHTTP :: Request_String -> IO (Result Response_String) -- | Like simpleHTTP, but acting on an already opened stream. simpleHTTP_ :: (Stream s) => s -> Request_String -> IO (Result Response_String) sendHTTP :: (Stream s) => s -> Request_String -> IO (Result Response_String) sendHTTP_notify :: (Stream s) => s -> Request_String -> IO () -> IO (Result Response_String) -- | Receive and parse a HTTP request from the given Stream. Should be used -- for server side interactions. receiveHTTP :: (Stream s) => s -> IO (Result Request_String) -- | Very simple function, send a HTTP response over the given stream. This -- could be improved on to use different transfer types. respondHTTP :: (Stream s) => s -> Response_String -> IO () -- | Session-level interactions over HTTP. -- -- The Network.Browser goes beyond the basic Network.HTTP -- functionality in providing support for more involved, and real, -- request/response interactions over HTTP. Additional features supported -- are: -- -- -- -- Example use: -- --
--   do 
--     rsp <- Network.Browser.browse $ do
--              setAllowRedirects True -- handle HTTP redirects
--              request $ getRequest "http://google.com/"
--     fmap (take 100) (getResponseBody rsp)
--   
module Network.Browser -- | BrowserState is the (large) record type tracking the current -- settings of the browser. data BrowserState connection -- | BrowserAction is the IO monad, but carrying along a -- BrowserState. data BrowserAction conn a -- | Proxy specifies if a proxy should be used for the request. data Proxy -- | Don't use a proxy. NoProxy :: Proxy -- | Use the proxy given. Should be of the form http://host:port, -- host, host:port, or http://host. Optional -- Authority to authenticate with the proxy as. Proxy :: String -> (Maybe Authority) -> Proxy -- | browse act is the toplevel action to perform a -- BrowserAction. Example use: browse (request (getRequest -- yourURL)). browse :: BrowserAction conn a -> IO a -- | request httpRequest tries to submit the Request -- httpRequest to some HTTP server (possibly going via a -- proxy, see setProxy.) Upon successful delivery, the URL -- where the response was fetched from is returned along with the -- Response itself. request :: (HStream ty) => Request ty -> BrowserAction (HandleStream ty) (URI, Response ty) -- | getBrowserState returns the current browser config. Useful -- for restoring state across BrowserActions. getBrowserState :: BrowserAction t (BrowserState t) -- | withBrowserAction st act performs act with -- BrowserState st. withBrowserState :: BrowserState t -> BrowserAction t a -> BrowserAction t a -- | setAllowRedirects onOff toggles the willingness to follow -- redirects (HTTP responses with 3xx status codes). setAllowRedirects :: Bool -> BrowserAction t () -- | getAllowRedirects returns current setting of the -- do-chase-redirects flag. getAllowRedirects :: BrowserAction t Bool -- | setMaxRedirects maxCount sets the maxiumum number of -- forwarding hops we are willing to jump through. A no-op if the count -- is negative; if zero, the max is set to whatever default applies. -- Notice that setting the max redirects count does not enable -- following of redirects itself; use setAllowRedirects to do so. setMaxRedirects :: Maybe Int -> BrowserAction t () -- | getMaxRedirects returns the current setting for the -- max-redirect count. If Nothing, the Network.Browser's -- default is used. getMaxRedirects :: BrowserAction t (Maybe Int) -- | Authority specifies the HTTP Authentication method to use for -- a given domain/realm; Basic or Digest. data Authority AuthBasic :: String -> String -> String -> URI -> Authority auRealm :: Authority -> String auUsername :: Authority -> String auPassword :: Authority -> String auSite :: Authority -> URI AuthDigest :: String -> String -> String -> String -> Maybe Algorithm -> [URI] -> Maybe String -> [Qop] -> Authority auRealm :: Authority -> String auUsername :: Authority -> String auPassword :: Authority -> String auNonce :: Authority -> String auAlgorithm :: Authority -> Maybe Algorithm auDomain :: Authority -> [URI] auOpaque :: Authority -> Maybe String auQop :: Authority -> [Qop] -- | getAuthorities return the current set of Authoritys -- known to the browser. getAuthorities :: BrowserAction t [Authority] setAuthorities :: [Authority] -> BrowserAction t () addAuthority :: Authority -> BrowserAction t () data Challenge ChalBasic :: String -> Challenge chRealm :: Challenge -> String ChalDigest :: String -> [URI] -> String -> Maybe String -> Bool -> Maybe Algorithm -> [Qop] -> Challenge chRealm :: Challenge -> String chDomain :: Challenge -> [URI] chNonce :: Challenge -> String chOpaque :: Challenge -> Maybe String chStale :: Challenge -> Bool chAlgorithm :: Challenge -> Maybe Algorithm chQop :: Challenge -> [Qop] data Qop QopAuth :: Qop QopAuthInt :: Qop -- | Algorithm controls the digest algorithm to, MD5 or -- MD5Session. data Algorithm AlgMD5 :: Algorithm AlgMD5sess :: Algorithm -- | getAuthorityGen returns the current authority generator getAuthorityGen :: BrowserAction t (URI -> String -> IO (Maybe (String, String))) -- | setAuthorityGen genAct sets the auth generator to -- genAct. setAuthorityGen :: (URI -> String -> IO (Maybe (String, String))) -> BrowserAction t () -- | setAllowBasicAuth onOff enables/disables HTTP Basic -- Authentication. setAllowBasicAuth :: Bool -> BrowserAction t () -- | setMaxErrorRetries mbMax sets the maximum number of attempts -- at transmitting a request. If Nothing, rever to default max. setMaxErrorRetries :: Maybe Int -> BrowserAction t () -- | getMaxErrorRetries returns the current max number of error -- retries. getMaxErrorRetries :: BrowserAction t (Maybe Int) -- | setMaxAuthAttempts mbMax sets the maximum number of -- authentication attempts to do. If Nothing, rever to default -- max. setMaxAuthAttempts :: Maybe Int -> BrowserAction t () -- | getMaxAuthAttempts returns the current max auth attempts. If -- Nothing, the browser's default is used. getMaxAuthAttempts :: BrowserAction t (Maybe Int) -- | setCookieFilter fn sets the cookie acceptance filter to -- fn. setCookieFilter :: (URI -> Cookie -> IO Bool) -> BrowserAction t () -- | getCookieFilter returns the current cookie acceptance filter. getCookieFilter :: BrowserAction t (URI -> Cookie -> IO Bool) -- | defaultCookieFilter is the initial cookie acceptance filter. -- It welcomes them all into the store :-) defaultCookieFilter :: URI -> Cookie -> IO Bool -- | userCookieFilter is a handy acceptance filter, asking the -- user if he/she is willing to accept an incoming cookie before adding -- it to the store. userCookieFilter :: URI -> Cookie -> IO Bool -- | Cookie is the Haskell representation of HTTP cookie values. -- See its relevant specs for authoritative details. data Cookie MkCookie :: String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Cookie ckDomain :: Cookie -> String ckName :: Cookie -> String ckValue :: Cookie -> String ckPath :: Cookie -> Maybe String ckComment :: Cookie -> Maybe String ckVersion :: Cookie -> Maybe String -- | getCookies returns the current set of cookies known to the -- browser. getCookies :: BrowserAction t [Cookie] -- | setCookies cookies replaces the set of cookies known to the -- browser to cookies. Useful when wanting to restore cookies -- used across browse invocations. setCookies :: [Cookie] -> BrowserAction t () -- | addCookie c adds a cookie to the browser state, removing -- duplicates. addCookie :: Cookie -> BrowserAction t () -- | setErrHandler sets the IO action to call when the browser -- reports running errors. To disable any such, set it to const -- (return ()). setErrHandler :: (String -> IO ()) -> BrowserAction t () -- | setErrHandler sets the IO action to call when the browser -- chatters info on its running. To disable any such, set it to const -- (return ()). setOutHandler :: (String -> IO ()) -> BrowserAction t () -- | setEventHandler onBrowserEvent configures event handling. If -- onBrowserEvent is Nothing, event handling is turned -- off; setting it to Just onEv causes the onEv IO -- action to be notified of browser events during the processing of a -- request by the Browser pipeline. setEventHandler :: Maybe (BrowserEvent ty -> BrowserAction ty ()) -> BrowserAction ty () -- | BrowserEvent is the event record type that a user-defined -- handler, set via setEventHandler, will be passed. It indicates -- various state changes encountered in the processing of a given -- RequestID, along with timestamps at which they occurred. data BrowserEvent ty BrowserEvent :: ClockTime -> RequestID -> String -> BrowserEventType ty -> BrowserEvent ty browserTimestamp :: BrowserEvent ty -> ClockTime browserRequestID :: BrowserEvent ty -> RequestID browserRequestURI :: BrowserEvent ty -> String browserEventType :: BrowserEvent ty -> BrowserEventType ty -- | BrowserEventType is the enumerated list of events that the -- browser internals will report to a user-defined event handler. data BrowserEventType ty OpenConnection :: BrowserEventType ty ReuseConnection :: BrowserEventType ty RequestSent :: BrowserEventType ty ResponseEnd :: ResponseData -> BrowserEventType ty ResponseFinish :: BrowserEventType ty type RequestID = Int -- | setProxy p will disable proxy usage if p is -- NoProxy. If p is Proxy proxyURL mbAuth, -- then proxyURL is interpreted as the URL of the proxy to use, -- possibly authenticating via Authority information in -- mbAuth. setProxy :: Proxy -> BrowserAction t () -- | getProxy returns the current proxy settings. getProxy :: BrowserAction t Proxy -- | setDebugLog mbFile turns off debug logging iff -- mbFile is Nothing. If set to Just fStem, -- logs of browser activity is appended to files of the form -- fStem-url-authority, i.e., fStem is just the prefix -- for a set of log files, one per host/authority. setDebugLog :: Maybe String -> BrowserAction t () out :: String -> BrowserAction t () err :: String -> BrowserAction t () -- | Lifts an IO action into the BrowserAction monad. ioAction :: IO a -> BrowserAction t a defaultGETRequest :: URI -> Request_String defaultGETRequest_ :: (BufferType a) => URI -> Request a formToRequest :: Form -> Request_String -- | uriDefaultTo a b returns a URI that is consistent with the -- first argument URI a when read in the context of the second -- URI b. If the second argument is not sufficient context for -- determining a full URI then anarchy reins. uriDefaultTo :: URI -> URI -> URI data Form Form :: RequestMethod -> URI -> [FormVar] -> Form type FormVar = (String, String) instance Eq Qop instance Show Qop instance Eq Algorithm instance Show Cookie instance Read Cookie instance Functor (BrowserAction conn) instance Monad (BrowserAction conn) instance Show (BrowserState t) instance Show Algorithm instance Eq Cookie