[ laravel爬虫实战--基础篇 ] guzzle带参数请求

Song4291 次浏览1个评论2017年11月03日

一、查询字符串参数,GET请求

你可以有多种方式来提供请求的查询字符串,你可以在请求的URI中设置查询字符串:

$response = $client->request(GET, http://baidu.com?foo=bar);

你也可以使用query请求参数来声明查询字符串参数:

$client->request(GET, http://baidu.com, [
    query => [foo => bar]
]);

提供的数组参数将会使用PHPhttp_build_query,最后,你可以提供一个字符串作为query请求参数:

$client->request(GET, http://httpbin.org, [query => foo=bar]);

二、上传数据

Guzzle为上传数据提供了一些方法。 你可以发送一个包含数据流的请求,将body请求参数设置成一个字符串、 fopen返回的资源、或者一个 Psr\Http\Message\StreamInterface的实例。

// Provide the body as a string.
$r = $client->request(POST, http://httpbin.org/post, [
    body => raw data
]);
// Provide an fopen resource.
$body = fopen(/path/to/file, r);
$r = $client->request(POST, http://httpbin.org/post, [body => $body]);
// Use the stream_for() function to create a PSR-7 stream.
$body = \GuzzleHttp\Psr7\stream_for(hello!);
$r = $client->request(POST, http://httpbin.org/post, [body => $body]);

// 上传JSON数据以及设置合适的头信息可以使用 json 请求参数这个简单的方式:

$r = $client->request(PUT, http://httpbin.org/put, [
    json => [foo => bar]
]);

三、POST/表单请求

除了使用body参数来指定请求数据外,Guzzle为发送POST数据提供了有用的方法。

发送表单字段

发送application/x-www-form-urlencoded``POST请求需要你传入form_params数组参数,数组内指定POST的字段。

$response = $client->request(POST, http://httpbin.org/post, [
    form_params => [
        field_name => abc,
        other_field => 123,
        nested_field => [
            nested => hello
        ]
    ]
]);

四、发送表单文件

你可以通过使用multipart请求参数来发送表单(表单enctype属性需要设置 multipart/form-data )文件, 该参数接收一个包含多个关联数组的数组,每个关联数组包含一下键名:

  • name: (必须,字符串) 映射到表单字段的名称。
  • contents: (必须,混合) 提供一个字符串,可以是 fopen 返回的资源、或者一个Psr\Http\Message\StreamInterface的实例。
$response = $client->request(POST, http://httpbin.org/post, [
    multipart => [
        [
            name     => field_name,
            contents => abc
        ],
        [
            name     => file_name,
            contents => fopen(/path/to/file, r)
        ],
        [
            name     => other_file,
            contents => hello,
            filename => filename.txt,
            headers  => [
                X-Foo => this is an extra header to include
            ]
        ]
    ]
]);

更多相关好文