将正文添加到 cfhttp 的正确方法

5 coldfusion cfhttp cfml lucee

我想使用 lucee/coldfusion 发出 API 请求。

我像这样设置我的令牌请求:

cfhttp(
    url="[myurl]"
    method="POST"
    result="token"          
) {
    cfhttpparam(type="header" name="host" value="[url]");
    cfhttpparam(type="body" name="client_id" value="[id]");
    cfhttpparam(type="body" name="client_secret" value="[secret]");
    cfhttpparam(type="body" name="grant_type" value="[credentials]");
    cfhttpparam(type="body" name="scope" value="[url]");
};
Run Code Online (Sandbox Code Playgroud)

但错误消息告诉我需要包含“grant_type”,所以我的正文似乎没有正确发送。

有人可以帮我吗?

编辑:

我也尝试过这个:

var body = {
    "host": "[url]",
    "client_id": "[id]",
    "client_secret": "[secret]",
    "grant_type": "[credentials]",
    "scope": "[url]"
}

// Token
cfhttp(
    url="[url]" 
    method="POST"
    result="token"          
) {
    cfhttpparam(type="header" name="host" value="[url]");
    cfhttpparam(type="body" value="#body.toJson()#");
};
Run Code Online (Sandbox Code Playgroud)

CfS*_*ity 5

您的第二次尝试是正确的方法,但您需要添加一个Content-Type标头,将正文指定为 JSON:

body = {
    "host": "[url]",
    "client_id": "[id]",
    "client_secret": "[secret]",
    "grant_type": "[credentials]",
    "scope": "[url]"
}
// Token
cfhttp(
    url="[url]" 
    method="POST"
    result="token"          
) {
    cfhttpparam(type="header", name="host", value="[url]");
    cfhttpparam(type="header", name="Content-Type", value="application/json");
    cfhttpparam(type="body", value="#body.toJson()#");
}
Run Code Online (Sandbox Code Playgroud)

显然,主体 JSON 也需要匹配 API 所期望的内容。