PHP 使用curl 发送到远程API

问题描述 投票:0回答:1

我想发布到这个API:

Fields:

Name    Type    
id* INTEGER 
date*   DATE    
hours*  FLOAT   

这是一个 json post 请求示例:

POST /api/v1/chase HTTP/1.1
Host: chamos.postos
Authorization: bearer 123123123
Accept: application/json
Content-Type: application/json; charset=utf-8
Content-Length: 63

{
    "id": 1,
    "date": "2023-12-12",
    "hours": "4.3"
}

这是我发送帖子请求的方式:

function call($url, $method = 'GET', $data= null) {
  $api = 'https://chamos.postos.com/api/v1/';
  $token = '123123123';
  $api_url = $api . $url;

  $curl = curl_init($api_url);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, [
      'Authorization: bearer ' . $token,
      'Accept: application/json',
  ]);

  if ($method === 'POST') {
      curl_setopt($curl, CURLOPT_POST, true);
      if ($requestData) {
          curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
      }
  }

  $res= curl_exec($curl);
  curl_close($curl);

  if (!$res) {
      return false;
  }

  return json_decode($res, true);
}
// some data that is passed down from js:
function post($formData) {
  $data= [
        'id' => $id,
        'date' => $date,
        'hours' => $hours
    ];
  return call('/chase', 'POST', $data);
}

不知何故,这是不正确的,因为我从远程 api 收到以下响应:

代码:400 详细信息:数组(3) 0:“ID” 1:“日期” 2小时” 长度:3 [[原型]]:数组(0) 消息:“缺少必填字段”

我在这里做错或遗漏了什么?

php json curl
1个回答
1
投票

根据样品帖子要求

POST /api/v1/chase HTTP/1.1
Host: chamos.postos
Authorization: bearer 123123123
Accept: application/json
Content-Type: application/json; charset=utf-8
Content-Length: 63

您需要在标题中添加

Content-Type: application/json; charset=utf-8
,因此请添加它,以便您的标题变成

curl_setopt($curl, CURLOPT_HTTPHEADER, [
      'Authorization: bearer ' . $token,
      'Accept: application/json',
      'Content-Type: application/json; charset=utf-8'
  ]);
© www.soinside.com 2019 - 2024. All rights reserved.