如何使用Wreq设置HTTP请求体?customMethod请求体设置咨询
Wreq库请求体设置指南
我来帮你梳理下Wreq里关于请求体的这两个常见问题,都是实际开发中很容易碰到的场景:
1. 如何使用Wreq库设置HTTP请求体?
Wreq的常用HTTP方法(比如post、put)本身就内置了请求体参数,你可以根据要发送的内容类型选择对应的方式:
发送JSON格式请求体:如果你的数据类型实现了ToJSON类型类,直接用
json函数把数据转换成请求体即可:import Network.Wreq import Data.Aeson (ToJSON) data User = User { name :: String, email :: String } deriving (ToJSON) main = do let user = User "Alice" "alice@example.com" response <- post "https://api.example.com/users" (json user) print response发送原始字节数据:用
Raw构造器指定Content-Type和字节流,适合上传二进制文件或自定义格式内容:import Network.Wreq import qualified Data.ByteString.Lazy as BL main = do let rawContent = BL.pack [0x48, 0x65, 0x6C, 0x6C, 0x6F] -- "Hello"的字节 body = Raw "application/octet-stream" rawContent response <- post "https://api.example.com/upload" body print response发送表单数据:用
form函数构造application/x-www-form-urlencoded格式的请求体:import Network.Wreq main = do let formData = form [("username", "alice"), ("password", "secure123")] response <- post "https://api.example.com/login" formData print response
2. 使用customMethod时如何设置请求体?
确实,customMethod不像post/put那样直接带请求体参数——它的设计是通过Options来配置请求的所有细节,包括请求体。你需要用setRequestBody函数(来自Network.Wreq.Types)把请求体注入到默认选项里,再传给customMethod。
举个实际例子,比如发送一个PATCH请求并携带JSON体:
import Network.Wreq import Network.Wreq.Types (setRequestBody) import Data.Aeson (ToJSON) data UserUpdate = UserUpdate { email :: String } deriving (ToJSON) main = do let updateData = UserUpdate "alice_new@example.com" -- 构造带请求体的Options opts = defaults & setRequestBody (json updateData) -- 发送PATCH请求 response <- customMethod "PATCH" "https://api.example.com/users/1" opts print response
如果要发送原始文本或二进制内容,同样用Raw构造器注入到Options中:
import Network.Wreq import Network.Wreq.Types (setRequestBody) import qualified Data.ByteString.Lazy as BL main = do let textBody = Raw "text/plain" (BL.pack "This is a custom method request") opts = defaults & setRequestBody textBody response <- customMethod "PUT" "https://api.example.com/custom" opts print response
简单来说,customMethod把请求配置的灵活性交给了Options,只要用setRequestBody把请求体绑定到选项上,就能实现和post/put一样的请求体效果。
内容的提问来源于stack exchange,提问作者Chris Stryczynski
相关产品推荐
相关产品推荐

