[英]file_get_contents of php, doesn't provide proper error response of a https request
我正在尝试从 HereMaps Geocoding API 做出 GET 响应,如下所示:
$hmaps_request = "https://geocode.search.hereapi.com/v1/geocode?apiKey={MY_API_KEY}&q=3891+Delwood+Drive%2C+Powell%2C+OH%2C+United+States;
$json_details = json_decode($hmaps_request);
当所有参数都正确且 JSON 格式也正确时,我得到了成功的响应。 但是当我提供错误的 API 密钥时,我得到如下错误:
local.ERROR:Error occurred while geocoding file_get_contents(https://geocode.search.hereapi.com/v1/geocode?apiKey={MY_API_KEY}&q=3891+Delwood+Drive%2C+Powell%2C+OH%2C+United+States): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
我使用 Postman 进行了相同的尝试,并得到了这样的正确错误响应,并带有 401 状态代码:
{
"error": "Unauthorized",
"error_description": "apiKey invalid. apiKey not found."
}
还尝试了 postman 提供的代码片段,但由于它是 HTTPS,我似乎必须提供证书。 使用 php 获得正确错误响应的任何方法。
您可以通过将http.ignore_errors
设置为 true 来更改此行为。
<?php
$opts = [
"http" => [
'ignore_errors' => true
]
];
$context = stream_context_create($opts);
$hmaps_request = file_get_contents("https://geocode.search.hereapi.com/v1/geocode?apiKey={MY_API_KEY}&q=3891+Delwood+Drive%2C+Powell%2C+OH%2C+United+States", false, $context);
$json_details = json_decode($hmaps_request);
/* Output
object(stdClass)#1 (2) {
["error"]=>
string(12) "Unauthorized"
["error_description"]=>
string(33) "apiKey invalid. apiKey not found."
}
*/
var_dump($json_details);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.