-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPClient.hs
More file actions
45 lines (41 loc) · 1.56 KB
/
HTTPClient.hs
File metadata and controls
45 lines (41 loc) · 1.56 KB
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
{-# LANGUAGE OverloadedStrings #-}
module HTTPClient where
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Network.HTTP
import Data.Maybe
import Network.URI
import Data.Aeson
import LastFM.JSON
import LastFM.Types
downloadFileWithMime :: String -> IO (Either String (Maybe B.ByteString,B.ByteString))
downloadFileWithMime url =
do resp <- simpleHTTP request
case resp of
Left x -> return $ Left ("Error connecting: " ++ show x)
Right r ->
case rspCode r of
(2,_,_) ->
case findHeader HdrContentType r of
Nothing -> return $ Right (Nothing, rspBody r)
Just mime -> return $ Right (Just (C.pack mime), rspBody r)
(3,_,_) -> -- A HTTP redirect
case findHeader HdrLocation r of
Nothing -> return $ Left (show r)
Just url -> downloadFileWithMime url
_ -> return $ Left (show r)
where request = Request {rqURI = uri,
rqMethod = GET,
rqHeaders = [],
rqBody = ""}
uri = fromJust $ parseURI url
{-
main :: IO ()
main = do
r <- downloadURL "http://www.popmatters.com/images/news_art/s/superchunk-majesty-shreddin.jpg"
case r of
Left x -> print x
Right (Just mime, resp) -> do BL.writeFile "test.jpg" resp
print mime
-}