我有这个 JSON 数据:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
我需要发布到 JSON URL: http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
如何使用 PHP 发送此 POST 请求?
您可以为此目的使用 CURL,请参阅示例代码:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
不使用任何外部依赖项或库:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response
是一个对象。可以像往常一样访问属性,例如$response->...
其中
$data
是包含您的数据的数组:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
警告:如果在 php.ini 文件中将
allow_url_fopen
设置设置为 Off
,这将不起作用。
如果您正在为 WordPress 开发,请考虑使用提供的 API:https://developer.wordpress.org/plugins/http-api/
请注意,当服务器在 HTTP 标头中返回
file_get_contents
时,Connection: close
解决方案不会关闭连接。
CURL 解决方案,另一方面,终止连接,因此 PHP 脚本不会因等待响应而被阻塞。
使用 CURL luke :) 说真的,这是最好的方法之一,你会得到回应。