簡體   English   中英

如何在 Guzzle 5 中發送 PUT 請求的參數?

[英]How do I send parameters for a PUT request in Guzzle 5?

我有此代碼用於為 POST 請求發送參數,該代碼有效:

$client = new GuzzleHttp\Client();
$request = $client->createRequest('POST', 'http://example.com/test.php');
$body = $request->getBody();

$request->getBody()->replaceFields([
    'name' => 'Bob'
]);

但是,當我將 POST 更改為 PUT 時,出現此錯誤:

Call to a member function replaceFields() on a non-object

這是因為 getBody 返回 null。

在正文中發送 PUT 參數實際上是否正確? 還是我應該在 URL 中執行此操作?

根據手冊

body選項用於控制包含請求的實體的主體(例如,PUT、POST、PATCH)。

put 'ing 的文檔化方法是:

$client = new GuzzleHttp\Client();

$client->put('http://httpbin.org', [
    'headers'         => ['X-Foo' => 'Bar'],
    'body'            => [
        'field' => 'abc',
        'other_field' => '123'
    ],
    'allow_redirects' => false,
    'timeout'         => 5
]);

編輯

根據您的評論:

您缺少createRequest函數的第三個參數 - 組成postput數據的鍵/值對數組:

$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);

當服務 ise 等待 json 原始數據時

$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);

或者

$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);

如果您使用的是Guzzle版本 6,則可以通過以下方式發出PUT 請求

$client = new \GuzzleHttp\Client();

$response = $client->put('http://example.com/book/1', [
    'query' => [
        'price' => '50',
    ]
]);

print_r($response->getBody()->getContents());

在 Guzzle 6 中,如果你想將 JSON 數據傳遞給你的 PUT 請求,那么你可以實現如下:

           $aObj = ['name' => 'sdfsd', 'language' => 'En'];

            $headers = [
                "User-Agent"    => AGENT,
                "Expect"        => "100-continue",
                "api-origin"    => "LTc",
                "Connection"    => "Keep-Alive",
                "accept"        => "application/json",
                "Host"          => "xyz.com",
                "Accept-Encoding"=> " gzip, deflate",
                "Cache-Control"=> "no-cache",
                "verify"        => false,
                "Content-Type" => "application/json"
            ];

          $client = new GuzzleHttp\Client([
            'auth'  => ['testUsername', 'testPassword'],
            'timeout'   => '10000',
            'base_uri'  => YOUR_API_URL,
            'headers' => $headers
        ]);

        $oResponse = $client->request('PUT', '/user/UpdateUser?format=json', ['body' => json_encode( $aObj, JSON_UNESCAPED_SLASHES)]);

        $oUser = json_decode( $oResponse->getBody());

暫無
暫無

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

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