簡體   English   中英

Guzzle POST給我“不支持HTTP方法'GET'”

[英]Guzzle POST gives me “does not support HTTP method 'GET'”

我正在嘗試使用Guzzle做一個簡單的API帖子。 但是,API始終返回錯誤“ UnsupportedApiVersion [Message] =>具有API版本'1'的請求資源不支持HTTP方法'GET'。”

在使用Content-Type:application / json標頭和簡單正文通過郵遞員進行簡單發布時:

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

它工作正常,我得到預期的結果。

但是,當使用以下代碼時,我一直在獲取方法GET不受支持的錯誤。


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

一些問題:


“ UnsupportedApiVersion [消息] =>具有API版本'1'的請求資源不支持HTTP方法'GET'

這指出了請求不匹配的問題-發送了GET而不是POST,這表明Guzzle使用的底層機制( cURL ,PHP流或自定義)存在問題,或者請求中存在某些問題迫使Guzzle進行GET。 您是否檢查過這是否確實在發生,並且API正確報告了? 您可以var_dump($res); 進行檢查,或通過$req = client->createRequest('post',...)將請求形成為單獨的變量,然后基於此StackOverflow QA在發送請求后檢查$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

暫無
暫無

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

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