以json格式将数据发送到外部api作为http帖子

时间:2019-03-21 05:46:30

标签: json api coldfusion coldfusion-10 cfhttp

我需要使用以下JSON格式将数据发送到外部API。

我需要一些与CFHTTP一起使用的正确ColdFusion语法的帮助,以实现此目标。

我在网上发现的搜索内容似乎远远不能满足我的要求

{
  "customer": {
    "first_name": "Steve",
    "last_name": "Lastnameson",
    "email": "steve.lastnameson@example.com",
    "phone": "+15142546011",
    "verified_email": true,
    "addresses": [
      {
        "address1": "123 Oak St",
        "city": "Ottawa",
        "province": "ON",
        "phone": "555-1212",
        "zip": "123 ABC",
        "last_name": "Lastnameson",
        "first_name": "Mother",
        "country": "CA"
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:0)

这里没有更详细的说明,这是一个通用示例,可​​以帮助您入门。

首先创建您的JSON数据并将其存储在变量中:

<cfsavecontent variable="JSONData">
{
  "customer": {
    "first_name": "Steve",
    "last_name": "Lastnameson",
    "email": "steve.lastnameson@example.com",
    "phone": "+15142546011",
    "verified_email": true,
    "addresses": [
      {
    "address1": "123 Oak St",
    "city": "Ottawa",
    "province": "ON",
    "phone": "555-1212",
    "zip": "123 ABC",
    "last_name": "Lastnameson",
    "first_name": "Mother",
    "country": "CA"
      }
    ]
  }
}
</cfsavecontent>

然后将该变量提交给api:

<cfhttp url="https://somedomain.com/api-specific-uri" method="post" timeout="30">
    <cfhttpparam type="header" name="content-type" value="application/json" />
    <cfhttpparam type="header" name="content-length" value="#Len(Trim(JSONData))#" />
    <cfhttpparam type="header" name="charset" value="utf-8" />
    <cfhttpparam type="body" value="#Trim(JSONData)#" />
</cfhttp>

然后,为了进行测试,您可以转储HTTP调用的结果:

<cfdump var="#cfhttp#" />

请注意,这是伪代码,尚未经过实际测试,您可能不需要所有这些标头,或者可能需要更多