(cURL / PHP) API Response - Invalid HTTP method used
Hopefully a simple question, I have tried to connect to my first REST API using PHP and cURL. My code is as follows:
<?php
$zooplaKey = "mykey";
$postcode = $_GET['postcode'];
$sendData = array('api_key' => $zooplaKey,
'postcode' => $postcode,
'output_type' => "postcode");
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://api.zoopla.co.uk/api/v1/average_area_sold_price.js');
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendData);
//cur开发者_JAVA技巧l_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
$zooplaInfo = json_decode($raw_json, true);
echo "<pre>";
print_r($zooplaInfo);
echo "</pre>";
?>
Run exactly as above I get a return of:
Array
( [error_string] => Invalid HTTP method used [error_code] => 2 )
Uncommenting //curl_setopt($curl, CURLOPT_POST, true);
or //curl_setopt($curl, CURLOPT_HTTPGET, true);
just returns a blank screen.
By using the following URL I am able to get a valid result (obviously I have had to blank the api key so this link is for structure purposes only) http://api.zoopla.co.uk/api/v1/average_area_sold_price.xml?api_key=mykey&postcode=ws12dn&output_type=postcode
Thanks all.
According to the Zoopla API Documentation, what you are trying to do is to:
Retrieve the average sale price for houses in a particular area.
Retrieval is done using a GET method in the REST standard. By using CURLOPT_POSTFIELDS
, cURL will automatically convert your request to a POST, which is invalid for retrieval. You should remove the post fields part, and do that instead:
curl_setopt($curl, CURLOPT_URL, 'http://full/url?'.http_build_query($sendData));
The parameters in the URL are being passed as GET. I would try appending the parameters to the CURLOPT_URL instead of putting them in the CURLOPT_POSTFIELDS array. The remote service probably requires the values be in the query string rather than being posted.
精彩评论