Google URL Shortener无法使用file_get_contents

时间:2014-07-05 11:16:29

标签: php google-app-engine file-get-contents url-shortener google-url-shortener

我正在尝试使用google api来缩短网址 我的网站托管在谷歌应用引擎上,所以我不能使用 CURL 必须使用 file_get_contents

$link = 'http://wwww.example.com';

$data = array('longUrl' => $link, 'key' => $apiKey);
$data = http_build_query($data);

$context = [
  'http' => [
  'method' => 'post',
  'header'=>'Content-Type:application/json',
  'content' => $data
  ]
];

$context = stream_context_create($context);
$result = file_get_contents('https://www.googleapis.com/urlshortener/v1/url', false, $context);

$json = json_decode($result);
print_r($json);

上面的代码给出错误

stdClass Object
(
    [error] => stdClass Object
        (
            [errors] => Array
                (
                    [0] => stdClass Object
                        (
                            [domain] => global
                            [reason] => parseError
                            [message] => Parse Error
                        )

                )

            [code] => 400
            [message] => Parse Error
        )

)

请纠正我在哪里做错了:(

2 个答案:

答案 0 :(得分:2)

API期望一个JSON编码的请求体(参见https://developers.google.com/url-shortener/v1/url#resource),所以你应该使用json_encode而不是http_build_query。

答案 1 :(得分:0)

对于遇到这种情况的任何其他人,我都可以使用以下内容:

$link = 'http://www.google.com';
$data = array('longUrl' => $link);

$context = [
  'http' => [
    'method' => 'post',
    'header'=>'Content-Type:application/json',
    'content' => json_encode($data)
  ]
];

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

// Return the JSONified results
$this->output->set_output($result);