Handling HTTP Query parameters in http-conduit

纵然是瞬间 提交于 2019-12-24 02:43:57

问题


I want to download the content of the URL

http://example.com/foobar?key1=value1&key2=value2

using http-conduit (GET request).

How can I do that:

a) Assuming I already know the full (i.e. encoded URL) b) If some parameters are dynamic and therefore not URL-encoded?

Note: This question was answered Q&A-style and therefore intentionally does not show any research effort.


回答1:


Regarding a):

You can use simpleHttp with an URL containing query parameters just like the example in the docs:

{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as LB

main :: IO ()
main =
    simpleHttp "http://example.com/foobar?key1=value1&key2=value2" >>= LB.putStr

Regarding b):

You need a list of key/value tuples of type [(ByteString, Maybe ByteString)] that contains your query parameters.

{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Conduit
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LB

queryParams :: [(ByteString, Maybe ByteString)]
queryParams = [
    ("key1", Just "value1"),
    ("key2", Just "value2")]

main :: IO ()
main = do
    request <- parseUrl "http://example.com/foobar"
    let request' = setQueryString queryParams request
    response <- withManager $ httpLbs request'
    LB.putStrLn $ responseBody response

Note: This requires at least http-conduit 2.1. Also note that it is recommended to reuse Manager instances where applicable.



来源:https://stackoverflow.com/questions/25145342/handling-http-query-parameters-in-http-conduit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!