laravel 安装guzzlehttp/guzzle


composer require guzzlehttp/guzzle


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

  • 用于构建查询字符串,POST请求,流式传输大型上传,流式传输大型下载,使用HTTP cookie,上传JSON数据等的简单界面...
  • 可以使用相同的接口发送同步和异步请求。
  • 为请求,响应和流使用PSR-7接口。这使您可以与Guzzle一起使用其他PSR-7兼容库。
  • 抽象出底层的HTTP传输,允许您编写环境和传输不可知的代码; 即不依赖于cURL,PHP流,套接字或非阻塞事件循环。
  • 中间件系统允许您增强和编写客户端行为。




    Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

    • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
    • 发送同步或异步的请求均使用相同的接口。
    • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
    • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
    • 中间件系统允许你创建构成客户端行为。
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET', 'https://api.github.com/user', [
        'auth' => ['user', 'pass']
    ]);
    echo $res->getStatusCode();
    // "200"
    echo $res->getHeader('content-type');
    // 'application/json; charset=utf8'
    echo $res->getBody();
    // {"type":"User"...'
    
    // 发送一个异步请求
    $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo 'I completed! ' . $response->getBody();
    });
    $promise->wait();
    

    安装Guzzle

    使用composer安装

    php composer.phar require guzzlehttp/guzzle:~6.0
    

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

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

    执行 composer update

    Guzzle基本使用

    • 发送请求
    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']
    ]);
    
    • 设置POST表单

    传入 form_params 数组参数

    $response = $client->request('POST', 'http://httpbin.org/post', [
        'form_params' => [
            'field_name' => 'abc',
            'other_field' => '123',
            'nested_field' => [
                'nested' => 'hello'
            ]
        ]
    ]);
    
    • 使用响应
    # 状态码
    $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

    同Guzzle的安装, 也适用Composer工具。

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

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

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

    执行安装

    API 单元测试

    我们在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']);
        }
        
    }
    

    运行测试

    在项目根目录执行命令

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

    总结

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





  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Laravel 中使用 GuzzleHttp/Guzzle 发送邮件可以通过以下步骤实现: 1. 安装 GuzzleHttp/Guzzle 可以使用 Composer 进行安装: ``` composer require guzzlehttp/guzzle ``` 2. 创建邮件发送类 在 app 目录下创建一个名为 MailSender 的类,代码如下: ```php <?php namespace App; use GuzzleHttp\Client; class MailSender { protected $client; public function __construct() { $this->client = new Client([ 'base_uri' => 'https://api.sendgrid.com/v3/', 'headers' => [ 'Authorization' => 'Bearer ' . env('SENDGRID_API_KEY'), 'Content-Type' => 'application/json' ] ]); } public function send($to, $subject, $content) { $response = $this->client->request('POST', 'mail/send', [ 'json' => [ 'personalizations' => [ [ 'to' => [ [ 'email' => $to ] ] ] ], 'from' => [ 'email' => 'sender@example.com' ], 'subject' => $subject, 'content' => [ [ 'type' => 'text/plain', 'value' => $content ] ] ] ]); return $response->getStatusCode(); } } ``` 其中,使用 GuzzleHttp\Client 创建一个 HTTP 客户端,设置 base_uri 为 SendGrid 邮件服务的 API 地址,headers 中包含 Authorization 和 Content-Type 信息。send() 方法接受收件人邮箱地址、邮件主题和邮件内容,使用 HTTP POST 请求发送邮件。 3. 在控制器中使用 MailSender 发送邮件 在需要发送邮件的控制器中,使用 MailSender 类发送邮件,示例代码如下: ```php <?php namespace App\Http\Controllers; use App\MailSender; use Illuminate\Http\Request; class MailController extends Controller { public function send(Request $request) { $to = $request->input('to'); $subject = $request->input('subject'); $content = $request->input('content'); $mailSender = new MailSender(); $statusCode = $mailSender->send($to, $subject, $content); return response()->json(['status' => $statusCode]); } } ``` 在 send() 方法中,从请求中获取收件人邮箱地址、邮件主题和邮件内容,然后实例化 MailSender 类并调用 send() 方法发送邮件。 4. 配置 SendGrid API 密钥 在 .env 文件中添加 SendGrid API 密钥: ``` SENDGRID_API_KEY=your_api_key_here ``` 至此,使用 GuzzleHttp/Guzzle 发送邮件的配置就完成了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值