5

我一直在查看Network.HTTP,但找不到创建正确 URL 编码的键/值对的方法。

例如,如何从[(key, value)]配对列表中生成所需的发布数据?我想这样的东西已经存在(可能隐藏在Network.HTTP包装中)但我找不到它,我宁愿不重新发明轮子。

4

3 回答 3

8

看看urlEncodeVars

urlEncodeVars :: [(String, String)] -> String
ghci> urlEncodeVars [("language", "Haskell"), ("greeting", "Hello, world!")]
"language=Haskell&greeting=Hello%2C%20world%21"
于 2012-07-31T02:59:15.207 回答
5

如果您正在尝试 HTTP POST 数据x-www-form-urlencodedurlEncodeVars可能不是正确的选择。该urlEncodeVars函数不符合application/x-www-form-urlencoded 编码算法有两点值得注意:

  • 它将空间编码%20+
  • 它编码*%2A而不是*

请注意以下函数旁边的注释Network.HTTP.Base

-- Encode form variables, useable in either the
-- query part of a URI, or the body of a POST request.
-- I have no source for this information except experience,
-- this sort of encoding worked fine in CGI programming.

有关一致编码的示例,请参阅包中的此函数hspec-wai

于 2016-05-03T15:42:30.387 回答
0

wreq我建议为此尝试。它提供FormParm数据类型,因此您可能希望将键值对转换为[FormParm]. 然后你可以使用这样的东西:

import qualified Data.ByteString.Char8 as C8
import Network.Wreq (post)
import Network.Wreq.Types (FormParam(..))

myPost = post url values where
  values :: [FormParam]
  values = [C8.pack "key" := ("value" :: String)]
  url = "https://some.domain.name"
于 2019-12-01T22:19:37.007 回答