如何用curl向指定地址POST一个JSON格式的数据2015-06-11 cnblogs 宵的天使昨天的一个任务,用POST 方式向一个指定的URL推送数据。以前都用的数组来完成这个工作。现在要求用json格式。感觉应该是一样的。开写。
<?php$post_url = "http://news.php";$post_data = json_encode($output_news);//$output_news处理好的数组$ch = curl_init();//初始化curl_setopt($ch, CURLOPT_TIMEOUT, "30");//超时时间curl_setopt($ch, CURLOPT_HTTPHEADER, array("Keep-Alive: 300","Connection: keep-alive")) ;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)");curl_setopt($ch, CURLOPT_POST,1);curl_setopt($ch, CURLOPT_URL,$post_url);curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);$contents = curl_exec($ch);if(curl_errno($ch)){//出错则显示错误信息print curl_error($ch);}curl_close($ch);承接页用$_POST接收,打印了一下发现是空的。上网搜索了一下发现PHP默认只识别application/x-www.form-urlencoded标准的数据类型。修改头信息也没有结果。。。
只能通过以下方式获得数据<?php//第一种方法$news= $GLOBALS["HTTP_RAW_POST_DATA"];//第二种方法$news=file_get_contents("php://input");
最后修改了修改了数据才能接收到。修改结果
<?phpcurl_setopt($ch,CURLOPT_POSTFIELDS,"news=".$post_data);?>这样承接页就用$_POST就可以接收到数据。