【问题标题】:(cURL / PHP) API Response - Invalid HTTP method used(cURL / PHP) API 响应 - 使用了无效的 HTTP 方法
【发布时间】:2011-02-16 05:25:04
【问题描述】:

希望是一个简单的问题,我尝试使用 PHP 和 cURL 连接到我的第一个 REST API。我的代码如下:

<?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);
//curl_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>";
?>

完全按照上面的方式运行,我得到的回报是:

数组
(
[error_string] => 使用了无效的 HTTP 方法
[错误代码] => 2
)

取消注释 //curl_setopt($curl, CURLOPT_POST, true);//curl_setopt($curl, CURLOPT_HTTPGET, true); 只会返回一个空白屏幕。

通过使用以下 URL,我可以获得有效结果(显然我不得不将 api 键设为空白,因此此链接仅用于结构目的)http://api.zoopla.co.uk/api/v1/average_area_sold_price.xml?api_key=mykey&postcode=ws12dn&output_type=postcode

谢谢大家。

【问题讨论】:

    标签: php api curl


    【解决方案1】:

    根据Zoopla API Documentation,您要做的是:

    检索特定区域内房屋的平均售价。

    检索是使用 REST 标准中的 GET 方法完成的。通过使用CURLOPT_POSTFIELDS,cURL 会自动将您的请求转换为 POST,无法检索。您应该删除帖子字段部分,然后改为:

    curl_setopt($curl, CURLOPT_URL, 'http://full/url?'.http_build_query($sendData));
    

    【讨论】:

    • 谢谢,从我关注的其他事情来看,我只看过 POSTFIELDS,现在就像一个魅力!
    【解决方案2】:

    URL 中的参数作为 GET 传递。我会尝试将参数附加到 CURLOPT_URL 而不是将它们放在 CURLOPT_POSTFIELDS 数组中。远程服务可能要求值在查询字符串中而不是被发布。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2015-05-21
      相关资源
      最近更新 更多