2015-06-22 109 views
2

我有什么,我觉得正确写入的代码,但每当我试图把它我得到来自谷歌拒绝的权限。谷歌短URL 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); 
} 
+0

你曾经通过卷曲试过吗? –

+0

我做到了,同样的结果 - 我也宁可不使用卷曲,除非我必须...... –

+0

我真的没有与谷歌urlshortener API的经验,所以我不能帮助任何进一步。但在任何情况下,我会去的卷曲,因为它是最快的(你可以搜索的file_get_contents,卷曲等方法之间的各种速度基准)。为响应 –

回答

1

看来我需要在URL

$result = file_get_contents("https://www.googleapis.com/urlshortener/v1/url?key=" . $apiKey, false, $context); 

这现在工作手动指定密钥。在API检查密钥(或缺少这些)时,必定会有一些有趣的事情发生。

编辑:为了在以后任何人,这是我的完整功能

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; 
} 
+0

感谢这个代码,工作非常好.... – Paramjeet