1

我正在尝试使用 google api 缩短 url 我的网站托管在 google app 引擎上,所以我不能使用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
        )

)

请纠正我做错的地方:(

4

2 回答 2

2

API 需要 JSON 编码的请求正文(请参阅https://developers.google.com/url-shortener/v1/url#resource),因此您应该真正使用 json_encode 而不是 http_build_query。

于 2014-07-07T05:38:14.660 回答
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);
于 2016-12-31T01:38:56.987 回答