php用post发送json并返回json数据实例

'课程',
    'loginName'=>'admin',
    'password'=>'admin'
);

//json也可以
$data_string =  json_encode($arr);
//普通数组也行
//$data_string = $arr;

echo $data_string;
//echo '
'; //curl验证成功 $ch = curl_init("http://501090.com/json"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string); 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); if (curl_errno($ch)) { print curl_error($ch); } curl_close($ch); echo $result; ?>
//curl验证成功
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://501090.com/json");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($data_string)
    )
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($curl);
curl_close($curl);
echo $res;
$ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string );
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);

做接口测试的过程中遇到的问题:

使用表单提交的方式:(可以是json,也可以是数组)

1)提交后将值转化为数组--->对数组转义json_encode($arr);成json数据可以实现,

2)提交后将值转化为数组--->不进行转义直接以数组的形式:两种方法都可以实现

直接对变量赋值得到数组(不可以json数据)

以上三种经验证都可以将数据输出成json格式

 "admin", 
              "startDate" => "2016-10-12 22:22:22",
              "loginName"=>'admin',
              "password"=>'admin',
              );
$data_string = $data;

$url = "http://501090.com/json";
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string );
$response = curl_exec($ch);
if (curl_errno($ch)) {
    print curl_error($ch);
}
curl_close($ch);
echo $response;

 

你可能感兴趣的:(json,post,php)