1

Google API で URL を短縮しようとしています。私のサイトは Google アプリ エンジンでホストされているため、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を参照)、実際には http_build_query の代わりに json_encode を使用する必要があります。

于 2014-07-07T05:38:14.660 に答える