首页 > 解决方案 > 如何使用 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。

标签: resthttphaskellpost

解决方案


根据 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

推荐阅读