我有这个代码用于发送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中执行此操作吗?
答案 0 :(得分:13)
根据the manual,
body 选项用于控制封闭实体的主体 请求(例如,PUT,POST,PATCH)。
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
函数的第三个参数 - 一组构成post
或put
数据的键/值对:
$request = $client->createRequest('PUT', '/put', ['body' => ['foo' => 'bar']]);
答案 1 :(得分:1)
当服务正在等待json原始数据时
$request = $client->createRequest('PUT', '/yourpath', ['json' => ['key' => 'value']]);
或
$request = $client->createRequest('PUT', '/yourpath', ['body' => ['value']]);
答案 2 :(得分:0)
如果您使用的是Guzzle版本6,则可以通过以下方式发出 PUT请求:
$client = new \GuzzleHttp\Client();
$response = $client->put('http://example.com/book/1', [
'query' => [
'price' => '50',
]
]);
print_r($response->getBody()->getContents());
答案 3 :(得分:0)
在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());