php通过curlpost发送json数据实例
例1
代码如下复制代码
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('api.local/rest/users');
($ch, CURLOPT_CUSTOMREQUEST,
"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,
$data_string);
curl命令发送post请求带参数curl_setopt($ch, CURLOPT_RETURNTRANSFER,
true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
例2
代码如下复制代码
function http_post_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array($return_code, $return_content);
}
$url  = "xx.xx";
$data = json_encode(array('a'=>1, 'b'=>2));
list($return_code, $return_content) = http_post_data($url, $data);
例3
代码如下复制代码
$data=' {
"button":[
{
"type":"click",
"name":"今⽇歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":"歌⼿简介",
"key":"V1001_TODAY_SINGER"
},
{
"name":"菜单",
"name":"菜单",
"sub_button":[
{
"type":"click",
"name":"hello ",
"key":"V1001_HELLO_WORLD"
},
{
"type":"click",
"name":"赞⼀下我们",
"key":"V1001_GOOD"
}]
}]
}';
$ch = curl_init($urlcon); //请求的URL地址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//$data JSON类型字符串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Content-Length: ' . strlen($data)));
$data = curl_exec($ch);
print_r($data);//创建成功返回:{"errcode":0,"errmsg":"ok"}
⼩结,我们发现最核⼼的⼀句代码就是Content-Type: application/json;这个是⽂件格式类型了。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。