gpt4 book ai didi

http - Haskell http响应结果不可读

转载 作者:可可西里 更新时间:2023-11-01 15:20:21 27 4
gpt4 key购买 nike

import Network.URI
import Network.HTTP
import Network.Browser

get :: URI -> IO String
get uri = do
let req = Request uri GET [] ""
resp <- browse $ do
setAllowRedirects True -- handle HTTP redirects
request req
return $ rspBody $ snd resp

main = do
case parseURI "http://cn.bing.com/search?q=hello" of
Nothing -> putStrLn "Invalid search"
Just uri -> do
body <- get uri
writeFile "output.txt" body

这是 haskell 输出和 curl 输出之间的差异

vimdiff

最佳答案

在这里使用 String 作为中间数据类型可能不是一个好主意,因为它会在读取 HTTP 响应和写入文件时引起字符转换。如果这些转换不一致,这可能会导致损坏,因为看起来它们在这里。

因为您只想直接复制字节,所以最好使用ByteString。我选择在这里使用惰性 ByteString,这样它就不必一次全部加载到内存中,而是可以惰性地流式传输到文件中,就像 String.

import Network.URI
import Network.HTTP
import Network.Browser
import qualified Data.ByteString.Lazy as L

get :: URI -> IO L.ByteString
get uri = do
let req = Request uri GET [] L.empty
resp <- browse $ do
setAllowRedirects True -- handle HTTP redirects
request req
return $ rspBody $ snd resp

main = do
case parseURI "http://cn.bing.com/search?q=hello" of
Nothing -> putStrLn "Invalid search"
Just uri -> do
body <- get uri
L.writeFile "output.txt" body

幸运的是,Network.Browser 中的函数被重载,因此对惰性字节串的更改只涉及将请求主体更改为 L.empty,替换 writeFile L.writeFile,以及更改函数的类型签名。

关于http - Haskell http响应结果不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com