Personal tools

Cookbook/Network programming

From HaskellWiki

< Cookbook(Difference between revisions)
Jump to: navigation, search
(note about hardcoding)
m (grammar)
Line 15: Line 15:
The following example do a POST via a proxy
The following example POSTs via a proxy.

Revision as of 05:25, 25 March 2010

The following example makes use of the Network and System.IO libraries to open a socket connection to Google and retrieve the Google home page.

    import Network;
    import System.IO;
    main = withSocketsDo $ do
	h <- connectTo "" (PortNumber 80)
	hSetBuffering h LineBuffering
	hPutStr h "GET / HTTP/1.1\nhost:\n\n"
	contents <- hGetContents h
	putStrLn contents
	hClose h

The following example POSTs via a proxy.

import Network.URI
import Network.HTTP
import Network.Browser
Just pollUri = parseURI "" -- WARNING: only works with hardcoded arguments like this one
body = "answer=42"
headers = [Header HdrContentType "application/x-www-form-urlencoded",
           Header HdrContentLength (show . length $ body)]
pollRq = Request {
 rqURI = pollUri, rqMethod = POST,
 rqHeaders = headers,
 rqBody = body
-- Default polipo setting
p = Proxy "localhost:8118" Nothing
main = browse $ do
     setProxy p
     request pollRq