PHP的HTTP客户端:Guzzle的简单使用
程序员文章站
2022-03-10 09:05:12
...
首先来一段官方文档对Guzzle的介绍:
然后cd到网站根目录,执行Composer命令下载Guzzle:(Linux环境)
composer require guzzlehttp/guzzle
下载完成后会生成一个vender文件夹:
在vender同级目录新建了一个guzzle.php来写例子。
【GET请求】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client();
//构造url
$url = 'https://www.baidu.com';
//get请求
$res = $client->request('GET', $url);
//返回状态码
echo $res->getStatusCode();
//连贯操作
//$res = $client->request('GET', $url)->getBody()->getContents();
?>
【POST请求】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client();
//构造url
$url = 'https://www.baidu.com';
//post请求
$res = $client->request('POST', $url, [
'form_params' => [
'name'=>'lws',
'sex'=>'nan'
]
]);
//返回状态码
echo $res->getStatusCode();
?>
【POST文件上传】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client();
//构造url
$url = 'https://www.baidu.com';
//post请求
$res = $client->request('POST', $url, [
'multipart' => [
[
'name'=>'name',
'contents'=>'lws'
],
[
'name'=>'sex',
'contents'=>'nan'
],
[
'name'=>'tupian',
'contents'=>file_get_contents('1.jpg'),
'filename'=>'lws.jpg'
]
]
]);
//返回状态码
echo $res->getStatusCode();
?>
【设置代理IP】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client();
//构造url
$url = 'https://www.baidu.com';
//设置代理请求
$res = $client->request('GET', $url, [
'proxy' => '111.22.33.44:6666'
]);
//返回状态码
echo $res->getStatusCode();
?>
【模拟请求头】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client(['headers'=>['referer'=>'https://www.baidu,com']]);
//构造url
$url = 'https://www.baidu.com';
//设置代理请求
$res = $client->request('GET', $url);
//返回状态码
echo $res->getStatusCode();
?>
【记录Cookie】
<?php
require './vendor/autoload.php';
//实例化客户端
$client = new GuzzleHttp\Client(['cookie'=>true]);
//构造url
$url = 'https://www.baidu.com';
//设置代理请求
$res = $client->request('GET', $url);
//返回状态码
echo $res->getStatusCode();
?>
上一篇: laravel seeder 数据填充