用curl向指定地址POST一个JSON格式的数据

  昨天的一个任务,用POST 方式向一个指定的URL推送数据。以前都用的数组来完成这个工作。

现在要求用json格式。感觉应该是一样的。开写。

 1 <?php
 2 $post_url = "http://news.php";
 3 $post_data = json_encode($output_news);//$output_news处理好的数组
 4 $ch = curl_init();//初始化
 5 curl_setopt($ch, CURLOPT_TIMEOUT, '30');//超时时间
 6 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Keep-Alive: 300','Connection: keep-alive')) ;
 7 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB7.4; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2)');
 8 curl_setopt($ch, CURLOPT_POST,1);
 9 curl_setopt($ch, CURLOPT_URL,$post_url);
10 curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
11 $contents = curl_exec($ch);
12 if(curl_errno($ch)){//出错则显示错误信息
13 print curl_error($ch);
14 }
15 curl_close($ch);

  承接页用$_POST接收,打印了一下发现是空的。上网搜索了一下发现PHP默认只识别application/x-www.form-urlencoded标准的数据类型。

修改头信息也没有结果。。。

只能通过以下方式获得数据
<?php
//第一种方法
$news    = $GLOBALS['HTTP_RAW_POST_DATA'];
//第二种方法
$news      =    file_get_contents("php://input");

 

 

  最后修改了修改了数据才能接收到。修改结果

<?php
curl_setopt($ch,CURLOPT_POSTFIELDS,"news=".$post_data);
?>
这样承接页就用$_POST就可以接收到数据

 

posted @ 2014-04-01 10:01  |小赵同学|  阅读(7684)  评论(0编辑  收藏  举报