使用php发送json post
我有以下json数据:使用php发送json post,php,json,post,curl,http-post,Php,Json,Post,Curl,Http Post,我有以下json数据: { userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021', itemKind: 0, value: 1, description: 'Saude', itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa' } 我需要发布到json url中: 使用php如何发送此post请求?使用CURL luke:)说真的,这是最好的方法之一,您可以获得响应。您可
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
我需要发布到json url中:
使用php如何发送此post请求?使用CURL luke:)说真的,这是最好的方法之一,您可以获得响应。您可以使用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中将允许url\u fopen设置设置为Off,则此操作将不起作用
如果您正在开发WordPress,请考虑使用提供的API:
提防FielyGETX内容解决方案不会关闭连接,因为服务器返回连接时应该关闭:HTTP报头中的关闭。
另一方面,CURL解决方案会终止连接,这样PHP脚本就不会因为等待响应而被阻塞。提供更多详细信息或代码我只需要发送带有userID、itemKind、value、description和itemID@GumboChrome不适合您;)@菲尔:JSON不是JavaScript,反之亦然。Chrome可能会接受该代码,因为它有一个JavaScript解释器。但是如果您使用
JSON.parse
来解析该代码,它肯定会失败。@Gumbo感谢您提供的额外信息。问题是没有引号的键吗?我的值比JSON多——是的,我也有JSON值。。我现在该怎么做?我总共要发布三个值:title=somevalue&hash=somevalue&json=json-VALUE。现在,如何使用php实现这一点?这在我的情况下不起作用()。我的nodej收到{}。你知道为什么吗?如果你对这个方法和本机的file\u get\u contents
方法进行基准测试,它们几乎是一样的speed@LIGHT-$content=http\u build\u查询(数组('key1'=>'value1','key2'=>'value2','json'=>json\u编码($array\u to\u been\u json))
您在前面准备的$array\u to\u been\u json=array(…)
中。curl并不总是启用的。。。有时你需要它来做老式的方式…我知道我已经晚了很多年,但是有可能用这个方法得到响应标题吗?太棒了,谢谢你提到在没有任何扩展的情况下这样做!没有扩展总是受欢迎的。我不知道WP对此有一个标准化的API。非常感谢您提供的信息@solarshado原始响应头可以通过获取。一个小的改进建议,您还可以将头放入数组中,特别是如果需要添加更多头,如授权。在这种情况下,不应添加“\r\n”。观察结果很好