我有一个API端点,我试图发布到。他们唯一的例子就是卷曲请求。我很难正确构建php json帖子。
这是卷曲请求:
reduce
这是我构建的PHP请求:
$ curl -XPOST https://myzbiz.pike13.com/api/v2/desk/people \
-H "Authorization: Bearer XXXXXXXXXXXXXXX" \
-H "Content-Type: application/json" \
-d '{
"person": {
"first_name": "Jane",
"last_name": "Client",
"email": "janeclient@example.com"
}
}'
它一直在$url2 = 'https://example.com/api';
$data2 = array('access_token'=>$jsonData->access_token, 'first_name'=>$userData[person][first_name], 'last_name'=>$userData[person][last_name], 'email'=>$userData[person][email]);
$options2 = array(
'http' => array(
'header' => "Authorization: Bearer tokenstringgoeshere\r\n" . "Content-Type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data2, JSON_FORCE_OBJECT),
)
);
$context2 = stream_context_create($options2);
$result2 = file_get_contents($url2, false, $context2);
$string2 = $result2;
$jsonData2 = json_decode($string2);
header('Content-Type: application/json');
echo json_encode($jsonData2);
行上抛出错误,如下所示:
file_get_contents()
答案 0 :(得分:1)
您可以使用PHP Curl
发出POST请求。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://myzbiz.pike13.com/api/v2/desk/people");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"person\": {\n \"first_name\": \"Jane\",\n \"last_name\": \"Client\",\n \"email\": \"janeclient@example.com\"\n }\n }");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Authorization: Bearer XXXXXXXXXXXXXXX";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
$result
将包含响应数据。