Ham*_*ava 5 php post json google-url-shortener guzzle
我想使用Google URL Shortener API。现在,我需要向 Google API 发送一个 JSON POST 请求。
我在 PHP 中使用 Guzzle 6.2。
这是我迄今为止尝试过的:
$client = new GuzzleHttp\Client();
$google_api_key = 'AIzaSyBKOBhDQ8XBxxxxxxxxxxxxxx';
$body = '{"longUrl" : "http://www.google.com"}';
$res = $client->request('POST', 'https://www.googleapis.com/urlshortener/v1/url', [
'headers' => ['Content-Type' => 'application/json'],
'form_params' => [
'key'=>$google_api_key
],
'body' => $body
]);
return $res;
Run Code Online (Sandbox Code Playgroud)
但它返回以下错误:
Client error: `POST https://www.googleapis.com/urlshortener/v1/url` resulted in a `400 Bad Request` response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
(truncated...)
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。我已经阅读了 Guzzle 文档和许多其他资源,但没有帮助!
你不需要form_params,因为Google需要简单的GET参数,而不是POST(你甚至不能这样做,因为你必须在主体类型之间进行选择:form_params创建application/x-www-form-urlencoded主体,body参数创建原始主体)。
所以只需替换form_params为query:
$res = $client->request('POST', 'https://www.googleapis.com/urlshortener/v1/url', [
'headers' => ['Content-Type' => 'application/json'],
'query' => [
'key' => $google_api_key
],
'body' => $body
]);
// Response body content (JSON string).
$responseJson = $res->getBody()->getContents();
// Response body content as PHP array.
$responseData = json_decode($responseJson, true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7279 次 |
| 最近记录: |