问题描述
我想下载网址的内容
http://example.com/foobar?key1=value1& key2 = value2
使用(GET请求)。
我该怎么做:
$ b $ a)假设我已经知道完整的(即编码的URL)
b)如果一些参数是动态的,因此不是URL编码的? b
$ b
注意:这个问题被回答为Q& A式,因此故意没有显示任何研究工作。
关于a):
您可以使用 simpleHttp
与一个包含查询参数的URL,就像文档中的示例一样:
$ b
{ - #LANGUAGE OverloadedStrings# - }
导入Network.HTTP.Conduit
将合格的Data.ByteString.Lazy导入为LB
mai n :: IO()
main =
simpleHttphttp://example.com/foobar?key1=value1&key2=value2>> = LB.putStr
code>
关于b):
您需要一个键/值列表包含您的查询参数的 [(ByteString,Maybe ByteString)]
类型的元组。
导入合格的Data.ByteString。 Lazy.Char8作为LB
queryParams :: [(ByteString,也许ByteString)]
queryParams = [
(key1,只是value1),
(key2,只是value2)]
main :: IO()
main = do
请求< - parseUrlhttp://example.com/ foobar
let request= setQueryString queryParams请求
响应< - withManager $ httpLbs请求'
LB.putStrLn $ responseBody响应
注意:这至少需要 http-conduit 2.1。
另请注意,建议在适用的情况下重复使用 Manager
实例。
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.
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.
这篇关于处理http-conduit中的HTTP查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!