如何在 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的方法是:

$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']]);

当服务等待 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());