Reputation: 888
I am trying to short url with google api my site is hosted on google app engine so i cant use CURL have to use 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);
Above code gives error
stdClass Object
(
[error] => stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[domain] => global
[reason] => parseError
[message] => Parse Error
)
)
[code] => 400
[message] => Parse Error
)
)
Please correct me where i am doing wrong :(
Upvotes: 1
Views: 1592
Reputation: 361
For anyone else that comes across this, I was able to get it working with the following:
$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);
Upvotes: 0
Reputation: 1412
The API is expecting a JSON-encoded request body (see https://developers.google.com/url-shortener/v1/url#resource), so you should really use json_encode instead of http_build_query.
Upvotes: 2