我如何使用 Guzzle6 发出此 POST 请求
How do I make this POST request with Guzzle6
我的 Guzzle5 代码大致如下:
$guzzle = new \GuzzleHttp\Client();
$request = $guzzle->createRequest('POST', $url);
$request->setHeader('Authorization', 'Bearer ' . $token);
$postBody = $request->getBody();
$postBody->setField('name', 'content');//several times
if (check for file) {
$postBody->addFile(new \GuzzleHttp\Post\PostFile('name', fopen(...));
}
$response = $guzzle->send($request);
设置 header 并可能添加文件,我不确定如何使用 Guzzle6 执行此操作。
这是从我的一个项目中复制的一些代码:
$client = new GuzzleHttp\Client();
$url = 'someurl.com/api';
$body = json_encode([
'variable1' => 'this',
'variable2' => 'that'
]);
$response = $client->post($url, [
'headers' => [
'header_variable1' => 'foo',
'header_variable2' => 'bar'
],
'json' => true,
'timeout' => 3,
'body' => $body
]);
$data = $response->json();
这里是官方文档中的一个示例,您如何设置 headers 并将文件添加到您的 POST 请求中 Guzzle 6:
$client = new \GuzzleHttp\Client();
$client->post('/post', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'data',
'headers' => ['X-Baz' => 'bar']
],
[
'name' => 'baz',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'qux',
'contents' => fopen('/path/to/file', 'r'),
'filename' => 'custom_filename.txt'
],
]
]);
multipart option sets the body of the request to a multipart/form-data form, if you don't need to work with files you can just use form_params instead of multipart 选项。
任何 headers 您可以通过帮助 headers 选项轻松设置。
您可以在此处找到其他信息 Guzzle Upgrade Guide (5.0 to 6.0)
我的 Guzzle5 代码大致如下:
$guzzle = new \GuzzleHttp\Client();
$request = $guzzle->createRequest('POST', $url);
$request->setHeader('Authorization', 'Bearer ' . $token);
$postBody = $request->getBody();
$postBody->setField('name', 'content');//several times
if (check for file) {
$postBody->addFile(new \GuzzleHttp\Post\PostFile('name', fopen(...));
}
$response = $guzzle->send($request);
设置 header 并可能添加文件,我不确定如何使用 Guzzle6 执行此操作。
这是从我的一个项目中复制的一些代码:
$client = new GuzzleHttp\Client();
$url = 'someurl.com/api';
$body = json_encode([
'variable1' => 'this',
'variable2' => 'that'
]);
$response = $client->post($url, [
'headers' => [
'header_variable1' => 'foo',
'header_variable2' => 'bar'
],
'json' => true,
'timeout' => 3,
'body' => $body
]);
$data = $response->json();
这里是官方文档中的一个示例,您如何设置 headers 并将文件添加到您的 POST 请求中 Guzzle 6:
$client = new \GuzzleHttp\Client();
$client->post('/post', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'data',
'headers' => ['X-Baz' => 'bar']
],
[
'name' => 'baz',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'qux',
'contents' => fopen('/path/to/file', 'r'),
'filename' => 'custom_filename.txt'
],
]
]);
multipart option sets the body of the request to a multipart/form-data form, if you don't need to work with files you can just use form_params instead of multipart 选项。
任何 headers 您可以通过帮助 headers 选项轻松设置。
您可以在此处找到其他信息 Guzzle Upgrade Guide (5.0 to 6.0)