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

老子叫甜甜 提交于 2019-12-04 20:08:26

问题


I have this code for sending parameters for a POST request, which works:

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

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

However, when I change POST to PUT, I get this error:

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

This is because getBody is returning null.

Is it actually correct to send PUT parameters in the body? Or should I do it in the URL?


回答1:


According to the manual,

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

The documented method of put'ing is:

$client = new GuzzleHttp\Client();

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

Edit

Based on your comment:

You are missing the third parameter of the createRequest function - an array of key/value pairs making up the post or put data:

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



回答2:


when service ise waiting json raw data

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

or

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


来源:https://stackoverflow.com/questions/28152906/how-do-i-send-parameters-for-a-put-request-in-guzzle-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!