File: HttpOld.hs

package info (click to toggle)
hugs98 98.200311-4
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 12,964 kB
  • ctags: 8,084
  • sloc: ansic: 67,521; haskell: 61,497; xml: 4,566; sh: 3,264; cpp: 1,936; yacc: 1,094; makefile: 915; cs: 883; sed: 10
file content (48 lines) | stat: -rw-r--r-- 1,231 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
--
-- Based on Mondrian example in DDJ.
--
module HttpOld where

import Dotnet 
import IOExts

--
-- NOTE: this version of the Http example accesses .NET
-- via primitive operations provided by the DotNet library
-- and not directly via the FFI. See Http.hs for a version
-- that does.
-- 

http :: String -> IO ()
http url = do
  req <- invokeStatic "System.Net.WebRequest" "Create" url
  if not (isNullObj req) then do
    rsp <- req # invoke "GetResponse" ()
    str <- rsp # invoke "GetResponseStream" ()
    ls  <- str # slurpString 
    putStrLn ls
   else
    putStrLn ("Unable to fetch "++ url)

slurpString :: Object a -> IO String
slurpString stream = do
  buf  <- mkVector ByteTy 200
  off  <- boxValue (0::Int)
  sz   <- boxValue (200::Int)
  let   
   go stream = do
     x    <- stream # invoke "Read" (buf, off, sz)
     stat <- hsValue x
     if (stat <= (0 :: Int))
      then return []
      else do
       ls <- bytesToUTF8 buf off x
       rs <- unsafeInterleaveIO (go stream)
       return (ls ++ rs)
  go stream

bytesToUTF8 :: Object a -> Object a -> Object a -> IO String
bytesToUTF8 byteArr off sz = do
  encUTF8 <- newObj "System.Text.UTF8Encoding" ()
  encUTF8 # invoke "GetString" (byteArr, off, sz)