Guzzle POST请求无法正常工作

5

我想使用 Google URL 缩短 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;

但是它返回以下错误:
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...)

希望能得到任何帮助。我已经阅读了 Guzzle 文档和其他很多资源,但都没有帮助!

3个回答

4

你不需要使用form_params,因为Google要求简单的GET参数,而不是POST (你甚至不能这样做,因为你必须在body类型之间选择: form_params创建application/x-www-form-urlencoded body,而body参数创建原始body)。

所以只需用query来替换form_params

$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);

1
响应 JSON 存储在响应体中。调用 $res->getBody()->getContents() 来查看它。 - Alexey Shokov
你真棒! :) - Hamed Kamrava

0

我无法进行POST请求,虽然情况不完全相同,但我在这里写下我的解决方案,以帮助其他人:

我需要发送一个带有类似于'request_data'的键的POST请求,我试图按照Guzzle文档所说的方式执行:

 $r = $client->request('PUT', 'http://test.com', [
'form_data' => ['request_data' => 'xxxxxxx']
 ]);

结果大致如下:

{'request_data':....}

但是我想要的是这样的:

 'request_data': {}

所以我最终发现做法是这样的:

    $client = new Client();

    $response = $client->request('POST', $url, [
        'body' => "request_data=" . json_encode([$yourData]),
        'headers' => [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ]
    ]);

像这样做,结果就是我预期的。


-1
手册上写着:

获取到 API 密钥后,你的应用程序可以在所有请求的 URL 后附加查询参数 key=yourAPIKey。

试着把 `"key=$google_api_key"` 添加到你的 URL 中。


那么 form_params 部分呢? - Hamed Kamrava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接