首页 > 解决方案 > 发出浏览器外请求时出现 Google 距离矩阵 URL 问题

问题描述

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Neuh%C3%B6fer+Damm+110,Germany&destinations=Vogelweide+8,Hamburg&key=YOUR_API_KEY

API 密钥将距离矩阵 API 链接到它。如果您使用自己的密钥,您将在浏览器中看到请求正常工作。但是,当您在代码中创建 HTTP::get(<>) 时,它会返回 404。目前,我正在使用 PHP Laravel 并遵循文档。

这是请求代码:

 $response = Http::get('https://maps.googleapis.com/maps/api/distancematrix/json
                ?units=metric
                &origins=Neuh%C3%B6fer+Damm+110,Germany
                &destinations=Vogelweide+8,Hamburg
                &key=MyKey`enter code here`'
            );

这是给定的响应:

Illuminate\Http\Client\Response {#576 ▼
  #response: GuzzleHttp\Psr7\Response {#618 ▼
    -reasonPhrase: "Not Found"
    -statusCode: 404
    -headers: array:8 [▼
      "Date" => array:1 [▶]
      "Content-Type" => array:1 [▶]
      "Server" => array:1 [▶]
      "Content-Length" => array:1 [▶]
      "X-XSS-Protection" => array:1 [▶]
      "X-Frame-Options" => array:1 [▶]
      "Server-Timing" => array:1 [▶]
      "Alt-Svc" => array:1 [▶]
    ]
    -headerNames: array:8 [▶]
    -protocol: "1.1"
    -stream: GuzzleHttp\Psr7\Stream {#617 ▶}

您是否遇到同样的问题?那么主要的问题是:当我们使用相同的有效链接时,我们错过了什么,所以我们得到了 NotFound?也许是标题?也许还有别的?我会继续寻找更合适的答案,但与此同时,我希望这会有所帮助

标签: phplaravelgoogle-distancematrix-api

解决方案


  1. 不要使用换行符,因为空格可能会添加到请求中。
  2. 与其在代码中扔进一大行不可读的 URL 和大量参数,不如尝试使用 GET 请求查询参数。我认为大多数 HTTP 客户端都可以做到这一点。在使用 Laravel PHP 框架的情况下,整个事情应该是这样的:
 $response = Http::get('https://maps.googleapis.com/maps/api/distancematrix/json', [
                'units' => 'metric',
                'origins' => 'Neuhöfer Damm 110,Germany',
                'destinations' => 'Vogelweide 8,Hamburg',
                'key' => YOUR_API_KEY'
            ]);

享受你的编码:)


推荐阅读