Php Google URL缩写器无法使用文件获取内容
我正试图用谷歌api短网址 我的网站托管在google app engine上,因此我不能使用CURL必须使用文件获取内容Php Google URL缩写器无法使用文件获取内容,php,google-app-engine,file-get-contents,url-shortener,google-url-shortener,Php,Google App Engine,File Get Contents,Url Shortener,Google Url Shortener,我正试图用谷歌api短网址 我的网站托管在google app engine上,因此我不能使用CURL必须使用文件获取内容 $link = 'http://wwww.example.com'; $data = array('longUrl' => $link, 'key' => $apiKey); $data = http_build_query($data); $context = [ 'http' => [ 'method' => 'post', 'h
$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
)
)
请纠正我的错误:(API需要一个JSON编码的请求体(请参阅),因此您应该真正使用JSON编码而不是http构建查询。对于遇到此问题的任何其他人,我能够使其与以下内容一起工作:
$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);
您是否定义了
$apiKey
?请尝试echo http\u build\u query($data);
查看它显示了什么。我已经定义了apiKey和http\u build\u query($data);也在做它的工作。我不知道问题实际发生在哪里?然后尝试“echo file\u get\u contents('',false,$context);`查看响应是什么。Thanx很多:)我没有注意到它是json格式的……总之比X多了很多:)(Y)