Search code examples
haskellpostgethttp-conduit

Haskell, Posting Values to Webpage


I'm trying to figure out how to perform GET's and POST's to websites in Haskell, and I seem to be having difficulty even figuring out how to do a simple POST. I'm sure this is a GET.

import Network.HTTP.Conduit
import Data.Conduit
import Data.Conduit.Binary (sinkFile)
import qualified Data.ByteString.Lazy as L
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Resource (runResourceT)

main :: IO ()
main = do
  runResourceT $ do

    case parseUrl"https://www.google.com" of
      Nothing -> liftIO $ putStr "Not a valid URL"
      Just req -> withManager $ \manager -> do
        res <- httpLbs req manager
        liftIO . L.putStr $ responseBody res

Can some one please show me an example of how to do a POST in haskell. I have tried to find a good example somewhere that I can understand but haven't had any luck! Can you please show me by using the Post Values "login" -> "James", "Pass" -> "MyPassword". Thanks in advance!


Solution

  • You need to change the Request data type to indicate that it is a POST method call. Also make sure that you have the latest http-client (version 0.3.6) installed as Michael Snoyman has added the setQueryString function quite recently.

    {-# LANGUAGE OverloadedStrings #-}
    import Network.HTTP.Conduit
    import Control.Monad.IO.Class
    import qualified Data.ByteString.Lazy as L
    import Control.Monad.Trans.Resource
    
    main :: IO ()
    main = do
      runResourceT $ do
        initReq <- parseUrl"https://www.google.com"
        let req = initReq {
              method = "POST"
              }
            req' = setQueryString [("login", Just "James"),("Pass", Just "MyPassword")] req
    
        withManager $ \manager -> do
          res <- httpLbs req' manager
          liftIO . L.putStr $ responseBody res