【问题标题】:How do I send JSON request AND post form data request together?如何一起发送 JSON 请求和发布表单数据请求?
【发布时间】: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 参数未在请求正文中发送)。

标签: php json rest postman


【解决方案1】:

几种可能性:

  1. 将令牌和密钥作为查询参数发送,将 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')) 获得正文。

  2. 在Authorization HTTP 标头(或任何其他自定义标头)中发送令牌和密钥:

    POST /my/api HTTP/1.1
    Authorization: MyApp TokenVal:KeyVal
    Content-Type: application/json
    
    {"notification": ...}
    

    您可以通过例如$_SERVER['HTTP_AUTHORIZATION'] 获取标头并自行解析。

  3. 制作请求正文的令牌和密钥部分(不是很喜欢):

    POST /my/api HTTP/1.1
    Content-Type: application/json
    
    {"key": val1, "token": val2, "notification": ...}
    

【讨论】:

  • 您好,规范是token和apiKey是POST数据。那么不应该使用解决方案#1,对吧?
  • 明确一点:解决方案 1 将数据放入 URL 查询字符串。那是 not “获取数据”,即使您在 PHP 中通过 $_GET 访问它。这对 PHP 来说是一个糟糕的命名。使用 POST 方法的 HTTP 请求是 POST 请求。 URL 查询字符串 中的数据是不是“GET 数据”。
  • 所以,不,没有理由不使用解决方案 1。
  • 并从字符串$token = $this -> input -> post('token'); 访问查询参数,这是正确的方式,对吧?
  • 我不知道您使用的是什么框架,所以我无法告诉您该框架必须使用什么 API 来访问 URL 查询参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多