简体   繁体   中英

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

Kindly help me with, how to post JSON Body and header to RESTFUL API in php? of following data.

 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"} 

Kindly help with solving my problem.

Here is your code, using 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);

And do what you want with the respons in $output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM