【问题标题】:Issue with Google Distance Matrix URL while making off-browser requests发出浏览器外请求时出现 Google 距离矩阵 URL 问题
【发布时间】:2021-04-06 15:55:41
【问题描述】:

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?也许是标题?也许还有别的?我会继续寻找更合适的答案,但同时,我希望这会有所帮助

【问题讨论】:

  • 您尝试访问的实际 URL 中是否包含所有空格和换行符?

标签: php laravel google-distancematrix-api


【解决方案1】:
  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'
            ]);

享受你的编码:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多