gpt4 book ai didi

php - Guzzle POST 请求不起作用

转载 作者:行者123 更新时间:2023-12-03 16:53:43 26 4
gpt4 key购买 nike

我想用 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;

但它返回以下错误:
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 文档和许多其他资源,但没有帮助!

最佳答案

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

所以只需更换 form_paramsquery :

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

关于php - Guzzle POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39199811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com