php中 curl模拟post发送json并接收json

来源:互联网 发布:网络语35是什么意思 编辑:程序博客网 时间:2024/05/16 06:25

本地模拟请求服务器数据,请求数据格式为json,服务器返回数据也是json. 由于需求特殊性, 如同步客户端的批量数据至云端, 提交至服务器的数据可能是多维数组数据了. 这时需要将此数据以一定的数据编码方式(json格式)来组织并提交.以便服务器很好地处理.

客户端curl模拟提交代码.

function http($url, $data = NULL, $json = false){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if (!empty($data)) {  if($json && is_array($data)){    $data = json_encode( $data );  }  curl_setopt($curl, CURLOPT_POST, 1);  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  if($json){ //发送JSON数据    curl_setopt($curl, CURLOPT_HEADER, 0);    curl_setopt($curl, CURLOPT_HTTPHEADER,      array(        'Content-Type: application/json; charset=utf-8',        'Content-Length:' . strlen($data))    );  } } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($curl); $errorno = curl_errno($curl); if ($errorno) {   return array('errorno' => false, 'errmsg' => $errorno); } curl_close($curl); return json_decode($res, true); }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

参数说明:
url:urldata: 数组形式的post数据
$json: 是否以json方式提交(1: 是, 0:否)

服务器端获取post数据代码:

print_r($_POST);
最后获取到的数据是空值.

上网搜索了一下发现PHP默认只识别application/x-www.form-urlencoded标准的数据类型,修改头信息也没有结果…只能通过以下方式获得数据

//第一种方法$post = $GLOBALS[‘HTTP_RAW_POST_DATA’];//第二种方法$post = file_get_contents(“php://input”);
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

最后修改后,数据才能接收到.

0 0
原创粉丝点击