Laravel—GuzzleHttp常用使用方法
Guzzle
Guzzle 是一个 PHP HTTP 客户端,致力于让发送 HTTP 请求以及与 Web 服务进行交互变得简单。
Github:https://github.com/guzzle/guzzle
Composer:https://packagist.org/packages/guzzlehttp/guzzle
简单发送请求
use GuzzleHttp\Client;
$client = new Client([
//根域名
'base_uri' => 'http://localhost',
// 超时
'timeout' => 2.0,
]);
$response = $client->get('/get'); //请求地址:http://localhost/get,请求方式为GET
$response = $client->post('/post');//请求地址:http://localhost/post,请求方式为POST
//暂时使用较多的就是这两种 更多的还未尝试 记录下 后续补充
POST 常规 发送请求
$response = $client->request('POST', 'http://localhost/post', [
'form_params' => [
'username' => '用户姓名',
'password' => '用户密码',
]
]);
POST JSON 发送请求
$response = $client->post('/set-username-data', [
'headers' => [//设置 header 为json
'Content-Type' => 'application/json'
],
'json' => [
'network_id' => 1,
'status' => 1,
'username' => 'aaa',
'password' => 'aaa'
]
]);
POST 文件 发送请求
$response = $client->post('set-file-data', [
'headers' => [//自定义 header 头
'Connection' => 'keep-alive',
'Content-Type' => 'application/json',
'Accept-Encoding' => 'gzip',
'Accept-Charset' => 'utf-8',
],
'multipart' => [//发送文件的数据 $filepath 为文件路径 fopen()函数为读取文件内容
[
'name' => 'binFile',
'contents' => fopen($filepath, 'r'),
'filename' => 'custom_filename.txt'//可选
],
],
]);
POST Cookies 请求
$client = new \GuzzleHttp\Client();
$url = 'https://www.baidu.com/getUserInfo';
$jar = new \GuzzleHttp\Cookie\CookieJar();
$cookie_domain = 'www.baidu.com';
$cookies = [
'BAIDUID' => '3XXXXXXXXXXXXXXXX',
];
$cookieJar = $jar->fromArray($cookies, $cookie_domain);
$res = $client->request('GET', $url, [
'cookies' => $cookieJar,
// 'debug' => true,
]);
$contents = $res->getBody()->getContents();//获取返回正文
响应
//1、获取返回正文,返回数据格式为字符串
//如返回为utf-8格式的 需要使用utf8_decode()函数 转译,以防乱码
//可以使用json_decode转成对象 用来其他业务上的判断
$contents = $response->getBody()->getContents();
//2、获取响应状态码 两种方式
$code = $response->getStatusCode(); // 200
$code = $response->getReasonPhrase(); //200
//3、判断header是否存在
$existence = $response->hasHeader('Content-Type');//返回 0(不存在) or 1(存在)
//4、获取某个header
$header = $response->getHeader('Content-Type');//返回格式为数组
//5、获取所有headers
$headers = $response->getHeaders();//获取全部的header
更多内容请查看手册
文章参考:Laravel ——GuzzleHttp 使用方法