我正在尝试学习如何使用Haskell和http-conduit通过HTTP/POST发送简单的字符串(这样它也可以与https一起工作),从文件中读取目标url,但在我看来,这仍然有点让人难以接受。
基本上就像我在这里学到的球拍一样:在Racket中发送HTTP POST
有人能给我一个小小的或最基本的例子吗?
发布于 2015-11-29 15:56:56
好的!奇怪的Haskell要注意的是Haskell的录音系统。当您使用URL字符串调用parseUrl时,http-conduit将给您返回一个包含一些默认值的Request记录,但是库希望您填写其余的内容。
例如,parseUrl总是返回设置为GET的HTTP方法的Request。应该由我们通过使用记录更新语法来覆盖该值--在这种情况下,您可以用新的键和值来追加大括号。
{-# LANGUAGE OverloadedStrings #-}
module Lib where
import Data.Aeson
import Network.HTTP.Client
buildRequest :: String -> RequestBody -> IO Request
buildRequest url body = do
nakedRequest <- parseRequest url
return (nakedRequest { method = "POST", requestBody = body })
send :: RequestBody -> IO ()
send s = do
manager <- newManager defaultManagerSettings
request <- buildRequest "http://httpbin.org/post" s
response <- httpLbs request manager
let Just obj = decode (responseBody response)
print (obj :: Object)如果您在GHCi中运行此操作,您应该能够将帖子发送到httpbin:
λ> :set -XOverloadedStrings
λ> send "hello there"
fromList [("origin",String "<snip>")
,("args",Object (fromList []))
,("json",Null)
,("data",String "hello there")
,("url",String "http://httpbin.org/post")
,("headers",Object (fromList [("Accept-Encoding",String "gzip")
,("Host",String "httpbin.org")
,("Content-Length",String "11")]))
,("files",Object (fromList []))
,("form",Object (fromList []))]您还需要OverloadedStrings扩展。没有它,就会发生两件事:
nakedRequest { method = "POST" }不会打打字机,因为库需要来自bytestring库的(严格的) ByteString。默认情况下,"POST"和所有字符串文本都具有String a.k.a [Char]类型。虽然有一个名为pack的函数接受String并返回ByteString,但打开重载的字符串要简单得多。编译器代表您自动调用pack。除此之外,还有更多的内容;有关细节,请参见奥利弗的博客文章。send "hello there"。send期望有一个RequestBody。尽管还有一个函数具有String -> RequestBody类型,但打开重载的字符串并让编译器为您调用它要容易得多。https://stackoverflow.com/questions/33983629
复制相似问题