如何在 php 中拨打 POST api

How to make a POST api call in php

我已经坚持了 2 天了。我在网上到处找答案,没找到。

我需要向 api 发出 POST 请求以注册用户。这是我得到的信息。

url: https://webbsite.com/api/register

HEADERS
..........................................................
Content-Type:application/json
Access-Token: randomaccesstoken

Body
..........................................................
{
  'email' => 'John.doe@gmail.com',
  'firstName' => 'John',
  'lastName' => 'Doe',
  'password' => "mypassword1"
}

Response
..........................................................
201
..........................................................
HEADERS
..........................................................
Content-Type:application/json

BODY
..........................................................
{
  "success": ture,
  "data": {
       "user_id": 1,
       "token": "randomusertoken"
  }
}

这就是我目前所拥有的。无论我做什么都会导致错误。我觉得这可能与 Access-Token 放置有关。很难找到使用访问令牌的示例。这是向 php 中的 api 发出 POST 请求的正确方法吗?

$authToken = 'randomaccesstoken';
$postData = array(
   'email' => 'John.doe@gmail.com',
   'firstName' => 'John',
   'lastName' => 'Doe',
   'password' => "mypassword1"

);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
                    "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));


    $response = file_get_contents('https://webbsite.com/api/register', FALSE, $context);

    if($response === FALSE){
        die('Error');
    }


    $responseData = json_decode($response, TRUE);


    print_r($responseData);

从给出的信息来看,您似乎只是发送了错误的 header 名称(尽管公平地说,Access-Token 不是标准的 header... )

尝试

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => "Access-Token: {$authToken}\r\n".
                    "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));