这个代码我写的是使用JSON中的post方法将数据发送到api,但作为回应我变得无效,任何人都可以告诉我代码中有什么问题。
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array(
"seatNumber"=>"40",
"name"=>"*****",
"age"=>"20",
"gender"=>"Male"
)
);
$data_string = json_encode($post);
echo $data_string;
$ch=url_init('http://api?username=*****');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,array('data'=>$data_string));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
echo'<pre>';
print_r($result);
来自api的回应
stdClass Object
(
[code] => 0
[errorCode] => ER30
[errorDesc] => Invalid Data
[message] => Failure
)
示例网址:
http://<ServerName>/bookbustickets/rest/json/2.0/tempbooking?username=****&password=******
示例输入数据:
data={"operatorCode":"2586",
"scheduleCode":"7Q52586C3YG8KJ350F2F5V264",
"travelDate":"2015-03-10",
"fromStationCode":"76",
"toStationCode":"75",
"boardingPointCode":"284936",
"droppingPointCode":"0000",
"email":"test@gmail.com",
"mobile":"9876543210",
"passenger":[
{
"seatNumber":"3",
"na 9 me":"Test",
"age":20,
"gender":"Male"},
{
"seatNumber":"4",
"name":"Test",
"age":20,
"gender":"Male"}
]
}
答案 0 :(得分:0)
好的问题是"passenger"
应该是一个对象数组,所以请尝试将代码更改为
$passenger1 = new stdClass();
$passenger1->seatNumber = "40";
$passenger1->name = "*****";
$passenger1->age = "20";
$passenger1->gender = "Male";
$passenger2 = new stdClass();
$passenger2->seatNumber = "41";
$passenger2->name = "*****";
$passenger2->age = "21";
$passenger2->gender = "Female";
$post = array(
"operatorCode"=>"9",
"scheduleCode"=>"84W92XC8LOBAF3KZP4",
"travelDate"=>"2015-03-20",
"fromStationCode"=>"84",
"toStationCode"=>"76",
"boardingPointCode"=>"191933",
"droppingPointCode"=>"0000",
"email"=>"*********",
"mobile"=>"*******",
"passenger"=>array( $passenger1, $passenger2 )
);
这将产生以下结果
{
"operatorCode":"9",
"scheduleCode":"84W92XC8LOBAF3KZP4",
"travelDate":"2015-03-20",
"fromStationCode":"84",
"toStationCode":"76",
"boardingPointCode":"191933",
"droppingPointCode":"0000",
"email":"*********",
"mobile":"*******",
"passenger":[
{
"seatNumber":"40",
"name":"*****",
"age":"20",
"gender":"Male"
},
{
"seatNumber":"41",
"name":"*****",
"age":"21",
"gender":"Female"
}
]
}
另外我要注意你为什么要使用
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
不会
curl_setopt($ch, CURLOPT_POST, true);
是更好的选择吗?