簡體   English   中英

Guzzle POST 請求不起作用

[英]Guzzle POST request not working

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

使用此鏈接可以在請求后獲得更好的最簡單的解決方案。

使用此鏈接- 單擊

我使用的方法與您相同,但方法更好。

我無法發出帖子請求,情況不完全相同,但我在這里寫下我的解決方案,以防萬一:

我需要使用像“request_data”這樣的鍵發送發布請求,我試圖按照 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'
        ]
    ]);

這樣做的結果是我所期望的。

手冊說如下:

獲得 API 密鑰后,您的應用程序可以將查詢參數 key=yourAPIKey 附加到所有請求 URL。

嘗試將 `"key=$google_api_key" 附加到您的 URL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM