[英]How to make a POST api call in php
I have been stuck on this for 2 day now. 我已经坚持了两天了。 I looked all over the internet for the answer and could not find it.
我在互联网上四处寻找答案,但找不到答案。
I need to make a POST request to an api to register users. 我需要向api发出POST请求以注册用户。 This is the info I was given.
这是我得到的信息。
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"
}
}
This is what I have so far. 到目前为止,这就是我所拥有的。 No matter what I do it results in an error.
无论我做什么,都会导致错误。 I feel it might have something to do with the Access-Token placement.
我觉得这可能与Access-Token放置有关。 It was hard to find an example that uses a access token.
很难找到使用访问令牌的示例。 Is this the correct way to make a POST request to an api in php?
这是向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);
From the info given, it looks like you're just sending the header name wrong (although to be fair, Access-Token isn't a standard header...) 从给出的信息来看,您似乎只是在发送错误的标头名称(尽管公平地说,Access-Token不是标准标头...)
Try 尝试
$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)
)
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.