上传数据
Guzzle为上传数据提供了一些方法。 你可以发送一个包含数据流的请求,将 body 请求参数设置成一个字符串、 fopen 返回的资源、或者一个 Psr\Http\Message\StreamInterface 的实例。
1. // Provide the body as a string.
2. $r = $client->request('POST', 'http://httpbin.org/post', [
3. 'body' => 'raw data'
4. ]);
6. // Provide an fopen resource.
7. $body = fopen('/path/to/file', 'r');
8. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
10. // Use the stream_for() function to create a PSR-7 stream.
11. $body = \GuzzleHttp\Psr7\stream_for('hello!');
12. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
上传JSON数据以及设置合适的头信息可以使用 json 请求参数这个简单的方式:
1. $r = $client->request('PUT', 'http://httpbin.org/put', [
2. 'json' => ['foo' => 'bar']
3. ]);
POST/表单请求
除了使用 body 参数来指定请求数据外,Guzzle为发送POST数据提供了有用的方法。
发送表单字段
发送 application/x-www-form-urlencoded POST请求需要你传入 form_params 数组参数,数组内指定POST的字段。
1. $response = $client->request('POST', 'http://httpbin.org/post', [
2. 'form_params' => [
3. 'field_name' => 'abc',
4. 'other_field' => '123',
5. 'nested_field' => [
6. 'nested' => 'hello'
7. ]
8. ]
9. ]);
发送表单文件
你可以通过使用 multipart 请求参数来发送表单(表单enctype属性需要设置 multipart/form-data )文件, 该参数接收一个包含多个关联数组的数组,每个关联数组包含一下键名:
- name: (必须,字符串) 映射到表单字段的名称。
- contents: (必须,混合) 提供一个字符串,可以是
fopen返回的资源、或者一个
Psr\Http\Message\StreamInterface 的实例。
1. $response = $client->request('POST', 'http://httpbin.org/post', [
2. 'multipart' => [
3. [
4. 'name' => 'field_name',
5. 'contents' => 'abc'
6. ],
7. [
8. 'name' => 'file_name',
9. 'contents' => fopen('/path/to/file', 'r')
10. ],
11. [
12. 'name' => 'other_file',
13. 'contents' => 'hello',
14. 'filename' => 'filename.txt',
15. 'headers' => [
16. 'X-Foo' => 'this is an extra header to include'
17. ]
18. ]
19. ]
20. ]);
