PHP的HTTP客户端Guzzle简单使用方法分析

2020-09-01 14:44:34

本文实例讲述了PHP的HTTP客户端Guzzle简单使用方法。分享给大家供大家参考,具体如下:

首先来一段官方文档对Guzzle的介绍:

然后cd到网站根目录,执行Composer命令下载Guzzle:(Linux环境)

composer require guzzlehttp/guzzle

下载完成后会生成一个vender文件夹:

在vender同级目录新建了一个guzzle.php来写例子。

【GET请求】

<?php   require './vendor/autoload.php';   //实例化客户端  $client = new GuzzleHttpClient();   //构造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 GuzzleHttpClient();    //构造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 GuzzleHttpClient();    //构造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 GuzzleHttpClient();    //构造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 GuzzleHttpClient(['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 GuzzleHttpClient(['cookie'=>true]);    //构造url  $url = 'https://www.baidu.com';   //设置代理请求  $res = $client->request('GET', $url);   //返回状态码  echo $res->getStatusCode();?>

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php socket用法总结》、《php字符串(string)用法总结》、《PHP数学运算技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《PHP网络编程技巧总结》

希望本文所述对大家PHP程序设计有所帮助。

相关文章 大家在看