Guzzle如何安装和使用

后端开发   发布日期:2023年06月23日   浏览次数:308

这篇文章主要介绍了Guzzle如何安装和使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Guzzle如何安装和使用文章都会有所收获,下面我们一起来看看吧。

一.什么是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 GuzzleHttpClient;
 
$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) . "
";
}
 
# 响应体
$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.我们在testsunitMyApiTest.php中定义了两个测试用例

<?php
 
class MyApiTest extends PHPUnit_Framework_TestCase
{
    protected $client;
 
    public function setUp()
    {
        $this->client = new GuzzleHttpClient( [
            '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

以上就是Guzzle如何安装和使用的详细内容,更多关于Guzzle如何安装和使用的资料请关注九品源码其它相关文章!