【问题标题】:Guzzle POST gives me "does not support HTTP method 'GET'"Guzzle POST 给我“不支持 HTTP 方法 'GET'”
【发布时间】:2019-10-21 21:01:11
【问题描述】:

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

当通过邮递员使用 Content-Type: application/json header 和一个简单的正文进行简单的发布时:

{
"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

【问题讨论】:

  • 很难准确指出可能出了什么问题,但是您是否尝试过将密钥 json 替换为 query
  • 不幸的是使用query给了我同样的结果

标签: php guzzle guzzle6


【解决方案1】:

几个问题:


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

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

查看this thread,看起来重定向是导致这种情况发生的一个常见原因 - 例如,如果您在 PHP 中的 URL 与在 Postman 中工作的 URL 不同,并且其中有错字.您也可以尝试禁止重定向发生,setting the option with 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 2014-01-16
    • 2019-12-17
    • 1970-01-01
    • 2023-02-05
    • 2020-07-19
    • 2013-11-14
    相关资源
    最近更新 更多