【发布时间】:2015-06-22 03:41:53
【问题描述】:
我有我认为正确编写的代码,但每当我尝试调用它时,我都会被 Google 拒绝。
file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
这不是速率限制或任何东西,因为我目前使用过的零...
我原以为这是由于 API 密钥不正确,但我已尝试多次重置它。首次应用 API 时没有停机时间吗?
或者我是否缺少标题设置或其他同样小的东西?
public function getShortUrl()
{
$longUrl = "http://example.com/";
$apiKey = "MY REAL KEY IS HERE";
$opts = array(
'http' =>
array(
'method' => 'POST',
'header' => "Content-type: application/json",
'content' => json_encode(array(
'longUrl' => $longUrl,
'key' => $apiKey
))
)
);
$context = stream_context_create($opts);
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url", false, $context);
//decode the returned JSON object
return json_decode($result, true);
}
【问题讨论】:
-
你用 cURL 试过了吗?
-
我做了,同样的结果 - 我也宁愿不使用 cURL,除非我真的必须...
-
我真的没有使用 Google urlshortener API 的经验,所以我无能为力。但无论如何,我会选择 cURL,因为它是最快的(您可以在 file_get_contents、curl 和其他方法之间搜索各种速度基准)。
-
感谢您的回复,最终运行的平台可能不支持 cURL,因此如果可以,请尽量避免。
标签: php rest google-url-shortener