Fro*_*her 73 php post json curl http-post
我有这些数据:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
Run Code Online (Sandbox Code Playgroud)
我需要发布到json网址: http:// domain/OnLeagueRest/resources/onleague/Account/CreditAccount
使用php如何发送此帖子请求?
Muh*_*han 129
您可以将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);
Run Code Online (Sandbox Code Playgroud)
Dav*_*lli 103
不使用任何外部依赖项或库:
$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 );
Run Code Online (Sandbox Code Playgroud)
$ 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'
);
Run Code Online (Sandbox Code Playgroud)
警告:如果在php.ini 中将allow_url_fopen设置设置为Off,则此方法无效.
如果您正在为WordPress进行开发,请考虑使用提供的API:http://codex.wordpress.org/HTTP_API