2

我有我认为正确编写的代码,但每当我尝试调用它时,我都会得到谷歌拒绝的许可。

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);
}
4

1 回答 1

1

看来我需要手动指定 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;
}
于 2015-06-22T04:59:57.700 回答