php - 发出浏览器外请求时出现 Google 距离矩阵 URL 问题
问题描述
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 和大量参数,不如尝试使用 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'
]);
享受你的编码:)
推荐阅读
- sql-server - MS Access 链接表显示不正确/错误的数据类型
- c# - ASP.NET Core MVC 发布表单数据未使用身份登录模型绑定?
- apache-spark - hdfs中的文件数不等于getNumPartitions的结果,怎么可能?
- html - Bootstrap 表单布局,2 列
- ios - 为什么我不能使用guard调用UIAlert函数
- php - 如何在不自动重新加载页面的情况下在引导模式中回显我的结果
- firebase - Firebase 数据库结构的建议
- javafx - 切换场景时JavaFX中的InvocationTargetException
- sql - 从连接列中查找所有单词的频率
- python - train_test_split 产生不一致的样本