如何使用GuzzleHttp(5.0版)发布帖子请求。
我正在尝试执行以下操作:
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
);
但是我收到了错误:
PHP致命错误:未捕获异常'InvalidArgumentException',并显示消息'无方法可以处理电子邮件配置密钥'
编辑:此方法现已在6.0中弃用。而不是'身体'使用'form_params'
试试这个
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'body' => array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
)
);
由于Marco的答案已被弃用,您必须使用以下语法(根据jasonlfunk的评论):
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$response = $client->request('POST', 'http://www.example.com/files/post', [
'multipart' => [
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'csv_header',
'contents' => 'First Name, Last Name, Username',
'filename' => 'csv_header.csv'
]
]
]);
// PUT
$client->put('http://www.example.com/user/4', [
'body' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
'timeout' => 5
]);
// DELETE
$client->delete('http://www.example.com/user');
对于长服务器操作很有用。
$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
如果您想了解更多详细信息,可以使用debug
选项,如下所示:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
// If you want more informations during request
'debug' => true
]);
qazxsw poi对新的可能性更加明确。
注意在Guzzle V6.0 +中,获取以下错误的另一个来源可能是错误地使用JSON作为数组:
传递“body”请求选项作为发送POST请求的数组已被弃用。请使用“form_params”请求选项发送application / x-www-form-urlencoded请求,或使用“multipart”请求选项发送multipart / form-data请求。
不正确:
Documentation
正确:
$response = $client->post('http://example.com/api', [
'body' => [
'name' => 'Example name',
]
])
正确:
$response = $client->post('http://example.com/api', [
'json' => [
'name' => 'Example name',
]
])
$response = $client->post('http://example.com/api', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
'name' => 'Example name',
])
])
加
$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
'body' => json_encode($dataArray)
]);
$response = $request->getBody();
在openssl.cafile
文件中