【问题标题】:Google Short URL API: ForbiddenGoogle 短网址 API:禁止使用
【发布时间】: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


【解决方案1】:

看来我需要手动指定网址中的键

$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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2015-04-30
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多