【问题标题】:Guzzle POST request not workingGuzzle POST 请求不起作用
【发布时间】:2017-01-05 02:30:44
【问题描述】:

我想使用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 文档和许多其他资源,但没有帮助!

【问题讨论】:

    标签: php json post guzzle google-url-shortener


    【解决方案1】:

    您不需要form_params,因为Google 需要简单的GET 参数,而不是POST(您甚至不能这样做,因为您必须在正文类型之间进行选择:form_params 创建application/x-www-form-urlencoded 正文和@ 987654324@ 参数创建原始正文)。

    所以只需将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);
    

    【讨论】:

    • 响应 JSON 在响应正文中。拨打$res->getBody()->getContents()查看。
    • 你太棒了:)
    【解决方案2】:

    我无法发出发布请求,情况并不完全相同,但我在这里写下我的解决方案以防万一:

    我需要使用像“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'
            ]
        ]);
    

    这样做的结果是我所期望的。

    【讨论】:

      【解决方案3】:

      手册说:

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

      尝试将 `"key=$google_api_key" 附加到您的网址。

      【讨论】:

      • 那么form_params 部分呢?
      猜你喜欢
      • 2018-12-06
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 2020-03-28
      相关资源
      最近更新 更多