所以这是一个API,应该在POST请求中接受以下参数:
token (as form data)
apiKey (as form data)
{
"notification": {
"id": 1,
"heading": "some heading",
"subheading": "some subheading",
"image": "some image"
}
} (JSON Post data)
现在我的问题是,我不能发送表单数据和JSON数据在同一个POST请求一起。因为,表单数据使用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作为请求体:
POST /my/api?token=val1&apiKey=val2 HTTP/1.1 Content-Type: application/json {"notification": ...}
在PHP中,您通过
$_GET
获得密钥和令牌,通过json_decode(file_get_contents('php://input'))
获得主体。 -
在
Authorization
HTTP报头(或任何其他自定义报头)中发送令牌和密钥:POST /my/api HTTP/1.1 Authorization: MyApp TokenVal:KeyVal Content-Type: application/json {"notification": ...}
您可以通过例如
$_SERVER['HTTP_AUTHORIZATION']
获取标题并自己解析它 -
使令牌和密钥成为请求体的一部分(不是很优选):
POST /my/api HTTP/1.1 Content-Type: application/json {"key": val1, "token": val2, "notification": ...}