首页 > 编程语言 >Guzzle PHP HTTP客户端使用

Guzzle PHP HTTP客户端使用

时间:2022-10-13 10:04:36浏览次数:50  
标签:body HTTP Guzzle client http PHP data response httpbin


  1. 什么是guzzle
  2. 安装Guzzle
  3. Guzzle基本使用
  4. 安装PHPUnit
  5. API单元测试

一.什么是guzzle

Guzzle是一个PHP HTTP客户端,可以轻松发送HTTP请求,并且可以轻松集成Web服务。

二.安装Guzzle

1.使用composer安装

composer require guzzlehttp/guzzle

2.或者编辑项目的composer.json文件,添加Guzzle作为依赖

 {
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}

执行 composer update

三.Guzzle基本使用

1.发送请求

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

2.设置查询字符串

$response = $client->request('GET', 'http://httpbin.org?foo=bar');

或使用 query 请求参数来声明查询字符串参数:

$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);

3.设置POST表单,传入 form_params 数组参数

$response = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'field_name' => 'abc',
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);

4.使用响应

# 状态码
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

# header
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}

// Get a header from the response.
echo $response->getHeader('Content-Length');

// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}

# 响应体
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();

四.安装PHPUnit

composer方式安装

composer global require "phpunit/phpunit=5.5.*"

或者在composer.json文件中声明对phpunit/phpunit的依赖

{
"require-dev": {
"phpunit/phpunit": "5.5.*"
}
}

五.API单元测试

1.我们在tests\unit\MyApiTest.php中定义了两个测试用例

<?php

class MyApiTest extends \PHPUnit_Framework_TestCase
{
protected $client;

public function setUp()
{
$this->client = new \GuzzleHttp\Client( [
'base_uri' => 'http://myhost.com',
'http_errors' => false, #设置成 false 来禁用HTTP协议抛出的异常(如 4xx 和 5xx 响应),默认情况下HTPP协议出错时会抛出异常。
]);
}

public function testAction1()
{
$response = $this->client->get('/api/v1/action1');
$body = $response->getBody();

//添加测试
$this->assertEquals(200, $response->getStatusCode());
$data = json_decode($body, true);
$this->assertArrayHasKey('errorno', $data);
$this->assertArrayHasKey('errormsg', $data);
$this->assertArrayHasKey('data', $data);
$this->assertEquals(0, $data['errorno']);
$this->assertInternalType('array', $data['data']);
}

public function testAction2()
{
$response = $this->client->post('/api/v1/action2', [
'form_params' => [
'name' => 'myname',
'age' => 20,
],
]);
$body = $response->getBody();

//添加测试
$this->assertEquals(200, $response->getStatusCode());
$data = json_decode($body, true);
$this->assertArrayHasKey('errorno', $data);
$this->assertArrayHasKey('errormsg', $data);
$this->assertArrayHasKey('data', $data);
$this->assertEquals(0, $data['errorno']);
$this->assertInternalType('array', $data['data']);
}

}

2.运行测试
在项目根目录执行命令

php vendor/bin/phpunit  tests/unit/MyApiTest.php

3.总结
通过Guzzle强大的功能,可以方便进行API单元测试。大家可以查看Guzzle文档,详细了解Guzzle的使用。


标签:body,HTTP,Guzzle,client,http,PHP,data,response,httpbin
From: https://blog.51cto.com/u_15052623/5752243

相关文章

  • 源码安装PHP扩展的两种方式
    Pear:php代码层面的扩展,PEAR的所有扩展都是用纯粹的PHP代码编写的,用户在下载到PEAR扩展以后可以直接使用将扩展的代码包含到自己的PHP文件中使用PECL:底层扩展而PECL是使用......
  • PHP Phar反序列化学习
    PHPPhar反序列化学习PharPhar是PHP的压缩文档,是PHP中类似于JAR的一种打包文件。它可以把多个文件存放至同一个文件中,无需解压,PHP就可以进行访问并执行内部语句。默认开......
  • HTTPS涉及的加密算法讲解
    前言从2015年左右开始,Google、Baidu、Facebook等互联网巨头,不谋而合地开始大力推行HTTPS,国内外的大型互联网公司很多也都已经启用了全站HTTPS为鼓励全球网站的HTTPS......
  • PHP基础
    PHP基础写在前面简单过一下php的基础语法,记录下与其他语言不同的地方,相同的就直接略过了。PHP标记风格<?php代码?>官方推荐风格<?代码?>短标记风格,需配置文件ph......
  • PhpStudy+PhpStorm远程调试
    PhpStudy+PhpStorm远程调试环境172.16.4.133:webserver(phpstudy)172.16.4.1:PhpStormPhpstudy配置php扩展钩上xdebugphp.ini修改配置[Xdebug]zend_extension=C:/Us......
  • ThinkPHP 3.2.3 学习
    ThinkPHP3.2.3学习环境要求PHP版本要求PHP5.3以上版本(注意:PHP5.3dev版本和PHP6均不支持)ThinkPHP目录结构下载官方的ThinkPHP后目录如下wwwWEB部署目录(或者子目......
  • dedecms系统php.ini register_globals must is Off的解决方案
    访问后台,报错如下图:成因:由于register_globals设置控制PHP变量访问范围,如果开启会引起不必要的安全问题,所以这里对其进行了强制关闭,如果站长的空间不支持,可以采用以下几......
  • 【Vegas原创】A系统(aspx)向B系统(asp)交互(XmLHttp)
    A系统:ImportsSystem.XmlPartialClass_DefaultClass_DefaultInheritsSystem.Web.UI.PageProtectedSubPage_Load()SubPage_Load(ByValsenderAsObject,By......
  • php 二维数组排序
    PHP二维数组排序(简单易懂版)1.先定义一个数组  $data[]=array('volume'=>67,'asd'=>'b','edition'=>2);$data[]=array('volume'=>86,'cc'=>'b','edition'=>1......
  • vscode配置一个PHP的开发环境(已验证)
    背景PhpStorm确实挺不错的,很多功能都集成了,相当方便。但PHPStorm大法固然好,但是至少有四个痛点:耗内存、打开JS慢(很多时候竟不能忍)、功能单一(想开发Java、Python、C?对不......