首页 > 解决方案 > Guzzle POST 给我“不支持 HTTP 方法 'GET'”

问题描述

我正在尝试使用 Guzzle 做一个简单的 API 帖子。然而,API 不断返回错误“UnsupportedApiVersion [Message] => API 版本为‘1’的请求资源不支持 HTTP 方法‘GET’。”

通过邮递员使用 Content-Type: application/json 标头和简单正文进行简单发布时:

{
"Username" : "xxxxxxx",
"Password" : "xxxxxxx",
"ApplicationID" : "xxxxxxx",
"DeveloperID" : "xxxxxxx"
}

它工作正常,我得到了预期的结果。

但是,当使用以下代码时,我不断收到方法 GET is not supported 错误。


public function connect()
{
   $client = new Client([
      'base_uri' => $this->url,
      'headers' => [
          'Accept' => 'application/json',
          'Content-Type' => 'application/json',
      ],
      'http_errors' => $this->getHttpErrors(),
    ]);
    return $client;
}

public function login()
{
    $client = $this->connect();
    $res = $client->post($this->url.'auth/signin', [
        'json' => [
            'ApplicationID' => xxxxxx,
            'DeveloperID'   => xxxxxx,
            'Username' => xxxxxx,
            'Password' => xxxxxx
        ]
    ]);

    $results = json_decode($res->getBody());
    return $results;
}

我没有使用“json”,而是尝试了“form_params”,它给了我相同的结果。

我正在使用 Guzzle 6.3.3

标签: phpguzzleguzzle6

解决方案


几个问题:


"UnsupportedApiVersion [Message] => API 版本为 '1' 的请求资源不支持 HTTP 方法 'GET'

这表明请求不匹配的问题 - 发送的是 GET 而不是 POST,这表明 Guzzle 使用的底层机制(cURL、PHP 流或自定义)存在问题,或者请求中存在强制拼命做一个 GET。您是否检查过这是否确实发生并且 API 是否准确报告?您可以根据此 StackOverflow QAvar_dump($res);进行检查,或者通过将请求形成为单独的变量$req = client->createRequest('post',...),然后 在发送请求后进行检查。$req->getMethod()

查看这个线程,看起来重定向是发生这种情况的一个常见原因 - 例如,如果您在 PHP 中的 URL 与在 Postman 中工作的 URL 不同,并且其中有错字。您还可以尝试通过使用 Guzzle 设置选项来禁用重定向:

$res = $client->post($this->url.'auth/signin', [
    'json' => [
        'ApplicationID' => xxxxxx,
        'DeveloperID'   => xxxxxx,
        'Username' => xxxxxx,
        'Password' => xxxxxx
    ],
    'allow_redirects' => false
]);

作为旁注,关键base_uri是要做到这一点,因此您所要做的就是在调用请求方法时指定路径。由于您已经将 base_uri 定义为$this->url,您可以将其转为:

$res = $client->post($this->url.'auth/signin', ...

进入:

$res = $client->post('auth/signin', ...

另外,请注意上述情况,因为这实际上是一种形成格式错误的 URL 的简单方法 - 特别是因为您没有分享$this->url代码中的值。


此外,您提到尝试使用form_params. 确保在这样做时也换掉Content-Type标题 - 例如设置为application/x-www-form-urlencoded.


推荐阅读