如何在php中将JSON主体和头发布到RESTFUL API


How to post JSON body and header to RESTFUL API in php?

请帮助我,如何在php中将JSON Body和header发布到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"} 

请帮我解决问题。

这是您的代码,使用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 中的响应执行您想要的操作