如何在Haskell中将HTTPS请求的响应体写入文件?

时间:2017-08-19 18:41:44

标签: haskell

我想将网页内容写入文件。但是我被困在文件写作部分。因为它给我一个类型错误。

import Control.Lens
import qualified Data.ByteString.Lazy as BL
import Network.Wreq

writeURIBodyToFile :: FilePath -> String -> IO()
writeURIBodyToFile filePath uri = do
  response <- get uri
  body <- (response ^. responseBody)
  BL.writeFile filePath body

这是错误:

Couldn't match type ‘IO BL.ByteString’ with ‘BL.ByteString’
Expected type: Getting
                 (IO BL.ByteString) (Response BL.ByteString) (IO BL.ByteString)
  Actual type: (BL.ByteString
                -> Const (IO BL.ByteString) BL.ByteString)
               -> Response BL.ByteString
               -> Const (IO BL.ByteString) (Response BL.ByteString)
In the second argument of ‘(^.)’, namely ‘responseBody’
In a stmt of a 'do' block: body <- (response ^. responseBody)

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的代码: body <- (response ^. responseBody)

应该是: let body = response ^. responseBody

解释您获得的类型错误:编译器说Couldn't match type ‘IO BL.ByteString’ with ‘BL.ByteString’。所以它用你编写的代码说的是期待IO ByteString,但你给了ByteString。这取决于<-块中的do运算符。这个,看起来像response ^. responseBody >>= \body -> <rest of code>

(>>=)的类型为Monad m => m a -> (a -> m b) -> m b。所以编译器认为你说response ^. responseBody的类型为m a或更具体IO a(其中aByteString)。

幸运的是,我们可以在let块中使用do并以这种方式指定body:)

相关问题