【发布时间】:2017-02-11 02:15:23
【问题描述】:
所以这是一个应该在 POST 请求中接受以下参数的 API:
token (as form data)
apiKey (as form data)
{
"notification": {
"id": 1,
"heading": "some heading",
"subheading": "some subheading",
"image": "some image"
}
} (JSON Post data)
现在我的问题是我无法在同一个 POST 请求中同时发送表单数据和 JSON 数据。因为,表单数据使用 Content-Type: application/x-www-form-urlencoded 而 JSON 需要有 Content-Type: application/json 我不知道如何将它们一起发送。我正在使用 Postman。
编辑:
所以api会调用函数create,我需要做这样的事情:
public function create() {
$token = $this -> input -> post('token');
$apiKey = $this -> input -> post('apiKey');
$notificationData = $this -> input -> post('notification');
$inputJson = json_decode($notificationData, true);
}
但我无法将 JSON 数据和表单数据放在一起。
我必须这样做才能获取 JSON 数据仅
public function create(){
$notificationData = file_get_contents('php://input');
$inputJson = json_decode($input, true);
} // can't input `token` and `apiKey` because `Content-Type: application/json`
【问题讨论】:
-
请发布您的代码。
-
您是否尝试过直接发送 JSON 而不将内容类型设置为
application/json? -
它看起来像一个表单帖子,有 3 个键和 3 个字符串值。
-
您是在尝试设计此 API,还是您尝试与之对话的现有 API……?
-
这个不是很清楚。问题不是“如何发送”,而是“服务器期望接收什么”。通常,JSON 请求将被服务器读取为请求的完整正文,格式为 JSON。 POST 数据被读取为请求的完整正文,格式为
key=val&key2=val2样式。两者格格不入,就像在说“我要素食培根三明治”。您需要知道服务器如何解释您的请求。服务器可能期望您的 JSON 正文带有 GET 样式参数(因为 GET 参数未在请求正文中发送)。