Php 谷歌短URL API:禁止
我有我认为正确编写的代码,但每当我尝试调用它时,我都会被谷歌拒绝Php 谷歌短URL API:禁止,php,rest,google-url-shortener,Php,Rest,Google Url Shortener,我有我认为正确编写的代码,但每当我尝试调用它时,我都会被谷歌拒绝 file_get_contents(https://www.googleapis.com/urlshortener/v1/url): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden 这不是一个利率限制或任何东西,因为我目前使用过零 我本以为这是由于API密钥不正确造成的,但我已经多次尝试重置它。首次应用API时没有停机时间,是吗 或者我缺少一个
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);
}
似乎我需要手动指定URL中的键
$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context);
这现在起作用了。API如何检查POST中的密钥(或者没有这样做),一定有点可笑
编辑:对于将来的任何人来说,这是我的全部功能
public static function getShortUrl($link = "http://example.com")
{
define("API_BASE_URL", "https://www.googleapis.com/urlshortener/v1/url?");
define("API_KEY", "PUT YOUR KEY HERE");
// Used for file_get_contents
$fileOpts = array(
'key' => API_KEY,
'fields' => 'id' // We want ONLY the short URL
);
// Used for stream_context_create
$streamOpts = array(
'http' =>
array(
'method' => 'POST',
'header' => [
"Content-type: application/json",
],
'content' => json_encode(array(
'longUrl' => $link,
))
)
);
$context = stream_context_create($streamOpts);
$result = file_get_contents(API_BASE_URL . http_build_query($fileOpts), false, $context);
return json_decode($result, false)->id;
}
你试过cURL吗?我试过了,结果是一样的——我也不想使用cURL,除非我真的必须这么做……我没有使用googleurlshortenerapi的经验,所以我不能再进一步了。但在任何情况下,我都会选择cURL,因为它是最快的(你可以在file\u get\u内容、cURL和其他方法之间搜索各种速度基准)。感谢您的响应,有可能最终运行它的平台不支持cURL,因此如果可以的话,我会尽量避免。