Laravel 替换 curl 神器(Guzzle中文文档)

阅读数: 2080 2018年08月10日

GET 请求

//GET 请求例子
$client = new Client();
$res = $client->request('GET', $url, [
			'headers' => [
				'Content-Type' => 'application/json',
			],
			'query' => [ //参数
				'page' => 1,
				'size' => '10'
			],
			'timeout' => 20, //超时时间(秒)
		]);
$res->getStatusCode(); // 获得接口反馈状态码
$body = $res->getBody(); //获得接口返回的主体对象
$body->getContents(); //获得主体内容

POST 请求

//POST 请求例子 1
$client = new Client();
$res = $client->request('POST', $url, [
			'headers' => [ //设置头信息
				'Content-Type' => 'application/json',
			],
			'json' => [ //参数
				'a' => 1,
				'name' => 'sss'
			],
			'timeout' => 20, //超时时间(秒)
		]);
$res->getStatusCode(); // 获得接口反馈状态码
$body = $res->getBody(); //获得接口返回的主体对象
$body->getContents(); //获得主体内容

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'
            ]
        ]
    ]
]);


更多请查看中文文档:http://guzzle-cn.readthedocs.io/zh_CN/latest/#guzzle

或英文文档:http://docs.guzzlephp.org/en/stable/


参考资料
http://docs.guzzlephp.org/en/stable/
http://guzzle-cn.readthedocs.io/zh_CN/latest/
https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html
phpriji.cn | 网站地图 | 沪ICP备17015433号-1