Difference between revisions of "Cookbook/Network programming"

From HaskellWiki
Jump to navigation Jump to search
 
m (fix up some weird formatting issues)
 
(3 intermediate revisions by one other user not shown)
Line 3: Line 3:
   
 
<haskell>
 
<haskell>
import Network;
+
import Network
import System.IO;
+
import System.IO
 
 
main = withSocketsDo $ do
+
main = withSocketsDo $ do
h <- connectTo "www.google.com" (PortNumber 80)
+
h <- connectTo "www.google.com" (PortNumber 80)
hSetBuffering h LineBuffering
+
hSetBuffering h LineBuffering
hPutStr h "GET / HTTP/1.1\nhost: www.google.com\n\n"
+
hPutStr h "GET / HTTP/1.1\nhost: www.google.com\n\n"
contents <- hGetContents h
+
contents <- hGetContents h
putStrLn contents
+
putStrLn contents
hClose h
+
hClose h
  +
</haskell>
  +
  +
The following example POSTs via a proxy.
  +
  +
<haskell>
  +
import Network.URI
  +
import Network.HTTP
  +
import Network.Browser
  +
  +
Just pollUri = parseURI "http://example.com/question?life&universe&everything" -- 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
 
</haskell>
 
</haskell>

Latest revision as of 20:37, 26 May 2011

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 "www.google.com" (PortNumber 80)
    hSetBuffering h LineBuffering
    hPutStr h "GET / HTTP/1.1\nhost: www.google.com\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 "http://example.com/question?life&universe&everything" -- 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