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

时间:2022-10-16 20:59:06
<?php
$arr = array(
'subject'=>'课程',
'loginName'=>'Durriya',
'password'=>'123'
);

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


echo $data_string;
//echo '<br>';

//curl验证成功

$ch = curl_init("http://test.api.com/");
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 = curl_init();
curl_setopt(
$curl, CURLOPT_URL, "http://hzgwyw.gensee.com/integration/site/training/room/created");
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;

以上是在随便一个php页面中可以实现的,在Thinkphp中所做的项目测试不支持头部的定义,然后又有一种新的curl格式也可以提交成功,但是都已数组的形式可以实现

$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格式

php同curl post 发送json并返回json数据实例php同curl post 发送json并返回json数据实例
<?php
$data = array("subject" => "nihao",
"startDate" => "2016-10-12 22:22:22",
"loginName"=>'admin@hzgwyw.com',
"password"=>'hzgwyw',
);
$data_string = $data;

$url = "http://hzgwyw.gensee.com/integration/site/training/room/created";
$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;
View Code