安装
composer require guzzlehttp/guzzle
发送GET请求
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); $response = $client->get('http://httpbin.org/get', [ 'query' => [ 'name' => 'Tom' ] ]); echo $response->getStatusCode(); // 200 $content = $response->getBody()->getContents(); print_r($content);
发送POST请求
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); $response = $client->post('http://httpbin.org/post', [ 'json' => [ 'name' => 'Tom' ] ]); echo $response->getStatusCode(); // 200 $content = $response->getBody()->getContents(); print_r($content);
发送异步请求
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); $promise = $client->getAsync('http://httpbin.org/get', [ 'query' => [ 'name' => 'Tom' ] ])->then(function ($response) { if ($response->getStatusCode() == 200) { echo $response->getBody()->getContents(); } }); // 如果不等待执行,则程序结束 $promise->wait();