rest - 如何使用 Haskell Network.HTTP.Simple 将字符串数组发送到 Web 服务器?
问题描述
我需要通过 POST 调用将字符串数组发送到服务器,如下所述:http: //pulsar.apache.org/admin-rest-api/ ?version=2.6.0&apiversion=v2#operation/setNamespaceReplicationClusters
数组应该看起来像
[“字符串”,“字符串”]
我想代码应该是这样的:
httpPostSetClustersNameSpace :: String -> String -> IO Int
httpPostSetClustersNameSpace endpoint clustersAsString = do
request <- parseRequest $ "POST " ++ endpoint
response <- httpLBS $ setRequestBodyLBS "????" request
let status = getResponseStatusCode response
return status
不知道该怎么做,我回顾了这篇文章,但不确定如何在 ByteString 中表示数组。
https://phuoc-thanh.github.io/2018/chapter04-reveal-the-secret/
我可以像这样做 JSON:
newtype ClusterInfo = ClusterInfo [String]
instance ToJSON ClusterInfo where
toJSON (ClusterInfo clusters) = object
[ "clusters" .= clusters
]
httpPostCluster :: String -> ClusterInfo -> IO Int
httpPostCluster endpoint clusterInfo = do
request <- parseRequest $ "POST " ++ endpoint
response <- httpLBS $ setRequestBodyJSON clusterInfo request
let status = getResponseStatusCode response
return status
但是字符串数组不是 JSON。所以,我不能使用 setRequestBodyJSON。
解决方案
根据 DarthFennec 的建议,我的解决方案是:
newtype ReplicationClustersInfo = ReplicationClustersInfo [String]
instance ToJSON ReplicationClustersInfo where
toJSON (ReplicationClustersInfo clusters) = toJSON clusters
setClustersNameSpace :: ReplicationClustersInfo -> String -> String -> String -> IO Int
setClustersNameSpace replicationClustersInfo host tenant namespace =
do
let endpoint = setNamespaceReplicationClustersEndpoint host tenant namespace
request <- parseRequest $ "POST " ++ endpoint
response <- httpLBS $ setRequestBodyJSON replicationClustersInfo request
let status = getResponseStatusCode response
return status
推荐阅读
- javascript - 如何在href中获取具有相同关键字的元素
- r - 如何在 R 中读取带有重复列的羽毛文件
- javascript - 如何在不下载图片的情况下将 p5 画布渲染到 Cloudinary
- c# - ASP.NET MVC 路由中的异常行为
- javascript - 元素仅在鼠标悬停在按钮上时跟随光标
- python - Firestore - 如何从 python 中的数组字段获取数据
- debugging - Safari 13.1 Web 检查器未附加模拟器
- php - 针对特定 php 版本错误的 Github 操作
- flutter - Flutter:创建一个填充应用栏标题区域的矩形
- javascript - React:调用函数,为什么第一个有效而第二个无效?