拨打谷歌地图API,但获得空响应

时间:2017-04-24 23:59:32

标签: php laravel api curl

我正试图在Laravel 5.3中与谷歌沟通cURL。 我得到一个空的响应,但200状态代码。 这是我的代码:

    public function directionGet($origin, $destination) {
    $callToGoogle = curl_init();
    $googleApiKey = '**************************';

    curl_setopt_array(
      $callToGoogle,
      array (
          CURLOPT_URL => 'http://maps.googleapis.com/maps/api/directions/json?origin='. $origin.'&destination=' . $destination . '&key= ' . $googleApiKey,
          CURLOPT_POST => true,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HEADER => 0
        )
    );
    $response = curl_exec($callToGoogle);
    curl_close($callToGoogle);
    return response()->json($response); 
}

1 个答案:

答案 0 :(得分:0)

我在代码中发现了一些问题 1.我认为谷歌要求你使用https而不是http来保证安全 2. $ in origin和$ destination需要在发送curl之前编码url格式 3. $ key后有1个空格

所以你试试这段代码

public function directionGet($origin, $destination) {

    $googleApiKey = '****************************';

    $url          = 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey;

    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => "GET",
        CURLOPT_HTTPHEADER     => [
            "cache-control: no-cache"
        ],
    ]);

    $response = curl_exec($curl);

    return $response; 
}

$origin = "75 9th Ave, New York, NY";
$destination = "MetLife Stadium Dr East Rutherford, NJ 07073";

$directions = directionGet($origin, $destination);

你问我代码中有什么问题 答案是 1.我将http更改为https 2.我添加修改您的标题(删除帖子标题,因为它使用了get方法) 3.我用url格式编码字符串(urlencode)

我修改了你的代码,例如

function directionGet($origin, $destination) {
    $callToGoogle = curl_init();
    $googleApiKey = '*************************';

    curl_setopt_array(
      $callToGoogle,
      array (
          CURLOPT_URL => 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_RETURNTRANSFER => true,
        )
    );
    $response = curl_exec($callToGoogle);
    curl_close($callToGoogle);
    return $response; 
}

希望这个帮助