如何在php中进行POST api调用

时间:2016-04-05 15:10:49

标签: php api http-post

我现在已经坚持了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);

1 个答案:

答案 0 :(得分:2)

根据给出的信息,看起来您只是发送标题名称错误(尽管公平,Access-Token不是标准标题...)

尝试

$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)
    )
));