如何在PHP中将REST身份和标题发布到RESTFUL API?

时间:2015-02-18 14:14:19

标签: php json curl

请帮助我,如何在php中将JSON Body和标题发布到RESTFUL API?以下数据。

 HTTP POST url : http://webapi.test.com/Bus/BlockSeat
 ConsumerKey : KEY
 ConsumerSecret: SECRETKEY

 bODY(json) : {"IsOfflineBooking": "false",
"TripId": "5927-0",
"BoardingId": "6",
"NoofSeats": "1",
"Fares": "717.5",
"SeatNos": "R5",
 "Titles": "Mr",
 "Names": "vijaykumar",
 "Ages": "27",
 "Genders": "M",
 "Address": "hyderabad",
 "UserType": "5",
 "Servicetax": "0"} 

请帮助解决我的问题。

1 个答案:

答案 0 :(得分:0)

这是您的代码,使用CURL:

$body = json_encode(array(
    "IsOfflineBooking" => "false",
    "TripId" => "5927-0",
    "BoardingId" => "6",
    "NoofSeats" => "1",
    "Fares" => "717.5",
    "SeatNos" => "R5",
    "Titles" => "Mr",
    "Names" => "vijaykumar",
    "Ages" => "27",
    "Genders" => "M",
    "Address" => "hyderabad",
    "UserType" => "5",
    "Servicetax" => "0"
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://webapi.test.com/Bus/BlockSeat");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                        
    'Content-Length: '.strlen($body)                                                                              
    'ConsumerKey: '.KEY,
    'ConsumerSecret: '.SECRETKEY                                                                        
));  

$output = curl_exec($ch);

curl_close($ch);

使用$output

中的响应执行您想要的操作