Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。Guzzle提供了简单的接口,构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
使用Composer安装:
composer require guzzlehttp/guzzle
或者编辑项目的composer.json文件,添加Guzzle作为依赖:
{ "require": { "guzzlehttp/guzzle": "~6.0" } }
然后执行composer update
发送请求
use GuzzleHttp\Client; $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'http://httpbin.org', // You can set any number of default request options. 'timeout' => 2.0, ]); $response = $client->get('http://httpbin.org/get'); $response = $client->delete('http://httpbin.org/delete'); $response = $client->head('http://httpbin.org/get'); $response = $client->options('http://httpbin.org/get'); $response = $client->patch('http://httpbin.org/patch'); $response = $client->post('http://httpbin.org/post'); $response = $client->put('http://httpbin.org/put');
设置查询字符串
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
或使用query
请求参数来声明查询字符串参数:
$client->request('GET', 'http://httpbin.org', [ 'query' => ['foo' => 'bar'] ]);
获取状态码:
$code = $response->getStatusCode(); // 200$reason = $response->getReasonPhrase(); // OK
判断头部信息:
if ($response->hasHeader('Content-Length')) { echo "It exists"; }
获取返回的头部信息:
echo $response->getHeader('Content-Length');// Get all of the response headers.foreach ($response->getHeaders() as $name => $values) { echo $name . ': ' . implode(', ', $values) . "\r\n"; }
使用getBody
方法可以获取响应的主体部分(body),主体可以当成一个字符串或流对象使用
$body = $response->getBody();
可以将返回体转换成字符串或者直接以字符串形式读取:
$stringBody = (string) $body; $content = $body->getContents();
有时我们需要将文件传送到另一个web服务上去,可以使用post文件流形式将文件数据传送到指定web目录。
$filename = 'a.jpg'; $data = fopen($filename, 'r'); $res = $client->request('POST', 'http://localhost:9999/upload.php', ['body' => $data]); $body = $res->getBody(); print_r($body->getContents());
接收上传文件的upload.php可以这样写:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = file_get_contents('php://input'); $file = file_put_contents('b.jpg', $data); if (FALSE === $file) { echo '上传成功'; } else { echo '上传失败'; } }
发送application/x-www-form-urlencoded
POST请求需要你传入form_params
数组参数,数组内指定POST的字段。
$res = $client->request('POST', 'http://localhost:9999/form.php', [ 'form_params' => [ 'field_name' => 'abc', 'other_field' => '123', 'nested_field' => [ 'nested' => 'hello' ] ] ]); $body = $res->getBody(); print_r((string)$body);
在接收端form.php使用$_POST
即可获取上传的表单数据。
有时候我们在于API接口交互的时候需要将数据以特定的json格式传给api,可以这样写:
$res = $client->request('POST', 'http://localhost:9999/json.php', [ 'json' => ['foo' => 'bar'] ]); $body = $res->getBody(); print_r((string)$body);
接收端json.php使用file_get_contents('php://input')
可获得提交的json数据。
使用Guzzle还可以发送异步请求以及并发请求,具体使用方法可参照Guzzle官方文档。
其实我们在一些特殊场景下可以使用Swoole的协程特性实现异步的http客户端,功能非常强大。
https://www.helloweba.net/php/596.html
-----------------------------------------------------------自己项目----------------------------------------------------
GuzzleHttp application/x-www-form-urlencoded
headers 上加 Authorization
$url = "http://xx.xx18.com/kxxord/bxxxupc"; $key = "4283A7F1244D4172Axxxxxx"; $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => $key, ]; $client = new \GuzzleHttp\Client(); $param = [ 'url'=>$domain_name, 'page_index'=>1, ]; $response = $client->request('POST', $url,['form_params'=>$param,'headers'=>$headers]); $response->getStatusCode(); // 200 $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' // $body = $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' $data = json_decode($response->getBody(), true);
$param_chinaz = [ 'key'=>$chinazApi_key, 'keyword'=>$user['word_by_domain'], 'domainName'=>$user['domain_name'], ]; $response_chinaz = $client->request('POST', $china_url,['form_params'=>$param_chinaz,'connect_timeout' => 120]);
-----------------------------------------------------封装的curl请求------------------------------------------------------------------
public function index() { //dump('ddd hello world');die; $time = time(); $arr = [ "高防vps","移动高防", "游戏高防服务器", "直播高防cdn", "高防主机", "cdn高防ddos", "高防独立服务器租用", "武汉安全公司", "高防", "杭州高防服务器", "浙江高防", "高防ip", "域名高防", "山东高防服务器", "传奇高防服务器", "武汉网络安全公司", "游戏盾", "青岛高防服务器", "武汉网络安全", "高防cdn购买", "硬防服务器", "高防护服务器", "网游高防服务器", "青岛bgp高防", "waf高级版", "青岛bgp", "高防IP", "主机waf", "免费高防ip", "waf 高防", "魔域高防服务器", "武汉高防服务器", "动态高防", "湖北高防服务器", "waf服务器", "武汉机房", "高防idc", "ip高防", "高防游戏盾", "扬州双线", "waf", "网络攻击", "防", "独立服务器", ]; foreach ($arr as $k => $v){ $chinazApi_key = "09f74f9089f6428c9fdfc65744572"; //chinazApi_key $china_url = "http://www.chinaz523.com/CallAPI/BaiduIndex"; $param_chinaz = [ 'key' => $chinazApi_key, 'keyword' =>$v, ]; // $response_chinaz = $client_chinaz->request('POST', $china_url, ['form_params' => $param_chinaz, 'connect_timeout' => 180,]); try { $res = $this->curl($china_url,"post",'',$param_chinaz); } catch (\Exception $e) { dump($e->getMessage());die; } $res1 = [ 'keyword'=>$v, 'res'=>$res, ]; // sleep(3); dump($res1); } dump(time()-$time." s"); } // $url 是请求的链接 // $postdata 是传输的数据,数组格式 private function curl($url = '', $method = 'get',$header = [],$param = []) { $val = strtolower($method) == 'get' ? 0 : 1; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, $val); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置为不是https也可以访问 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //设置header头 if ( !empty($header) ) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } //设置post的数据包,即传参 if(!empty($param) && $val == 1){ curl_setopt($ch, CURLOPT_POSTFIELDS, $param); } if (isset($header['header'])){ $header_info = curl_getinfo($ch); var_dump($header_info); } $result = curl_exec($ch); curl_close($ch); return $result; }
-------------------------------------------能成---------------------------------------------------------------------------------------
$url = "http://xxxx.com/keyword/xxupc"; $key = "5B4FE278B5EF43xx78csdsD"; $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => $key, ]; $client = new \GuzzleHttp\Client(['connect_timeout' =>10,'timeout' => 10]); //设置超时时间 $param = [ 'url'=>$domain_name, ]; $response = $client->request('POST', $url,['form_params'=>$param,'headers'=>$headers]); $response->getStatusCode(); // 200 $response->getHeaderLine('content-type'); // 'application/json; charset=utf8' // $body = $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}' $data = json_decode($response->getBody(), true);
今天使用Guzzle的HTTP客户端,遇到问题,看到这个比较好,转载一下,来源:搬砖小伙子
推荐