[ laravel爬虫实战--基础篇 ] guzzle带参数请求
Song •
4291 次浏览 •
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]
]);
提供的数组参数将会使用PHP
的http_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
]
]
]
]);
更多相关好文
-
laravel中distinct()的使用方法与去重 2017-09-11
-
Laravel将view缓存为静态html,laravel页面静态缓存 2021-10-09
-
[ laravel爬虫实战--基础篇 ] guzzle描述与安装 2017-11-01
-
[ 配置教程 ] 在ubuntu16.04中部署LNMP环境(php7+maridb且开启maridb远程以及nginx多域名访问 )并配置laravel环境 2017-07-18
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
热门文章
-
mysql如何给运营人员添加只有查询权限的账号 2024-12-02
-
Mac 安装mysql并且配置密码 2024-11-20
-
阿里云不同账号(跨账号)ECS服务器同地域如何实现免费内网互通? 2024-11-12
-
electron安装使用better-sqlite3并解决NODE_MODULE_VERSION xxx. This version of Node.js requires 2024-11-06
-
Zerotier+Moon+Nginx实现内网穿透搭建网站 2024-08-23
花生壳绑定ubuntu服务器?