代码之家  ›  专栏  ›  技术社区  ›  zac

为什么会出现错误“此服务需要API密钥”?

  •  0
  • zac  · 技术社区  · 6 年前

    我试图用下面的php代码向google places api发送post请求,但是我得到了一个错误

    字符串(141)“{”错误消息“:”此服务需要API密钥。“, “HTML属性”:[],“结果”:[],“状态”:“请求被拒绝” }

    <?php
    include_once 'configuration.php';
    
    $url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
    $data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
    
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) { /* Handle error */ }
    
    var_dump($result);
    

    问题在哪里?

    1 回复  |  直到 6 年前
        1
  •  2
  •   ariefbayu    6 年前

    如中所述 documentation of text search ,参数需要在get方法中。你是邮递的。

    A Text Search request is an HTTP URL of the following form:
    
        https://maps.googleapis.com/maps/api/place/textsearch/output?parameters
    
    ...
    
    Certain parameters are required to initiate a search request. As is standard in URLs, all parameters are separated using the ampersand (&) character.
    

    请改为尝试此代码段:

    <?php
    include_once 'configuration.php';
    
    $url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' . urlencode('restaurants in Sydney') . '&key=' . API_KEY;
    
    $result = file_get_contents($url);
    if ($result === FALSE) { /* Handle error */ }
    
    var_dump($result);
    

    要使用数组参数,请更改 $url 到:

    $data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
    $url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?' . http_build_query($data);