如何在 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?

根据the manual

The body option is used to control the body of an entity enclosing request (e.g., PUT, POST, PATCH).

记录的 puting 方法是:

$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 数据的 key/value 对数组:

$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());