发送请求

你可以使用Guzzle的 GuzzleHttp\ClientInterface 对象来发送请求。

创建客户端

  1. use GuzzleHttp\Client;
  2. $client = new Client([
  3. // Base URI is used with relative requests
  4. 'base_uri' => 'http://httpbin.org',
  5. // You can set any number of default request options.
  6. 'timeout' => 2.0,
  7. ]);

Client对象可以接收一个包含参数的数组:

base_uri

(string|UriInterface) 基URI用来合并到相关URI,可以是一个字符串或者UriInterface的实例,当提供了相关uri,将合并到基URI,遵循的规则请参考 RFC 3986, section 2 章节。

  1. // Create a client with a base URI
  2. $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
  3. // Send a request to https://foo.com/api/test
  4. $response = $client->request('GET', 'test');
  5. // Send a request to https://foo.com/root
  6. $response = $client->request('GET', '/root');

不想阅读RFC 3986?这里有一些关于 base_uri 与其他URI处理器的快速例子:

base_uriURIResult
http://foo.com/barhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/bar
http://foo.com/foobarhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/foo/bar
http://foo.comhttp://baz.comhttp://baz.com
http://foo.com/?barbarhttp://foo.com/bar

handler

传输HTTP请求的(回调)函数。 该函数被调用的时候包含 Psr7\Http\Message\RequestInterface 以及参数数组,必须返回 GuzzleHttp\Promise\PromiseInterface ,成功时满足 Psr7\Http\Message\ResponseInterfacehandler 是一个构造方法,不能在请求参数里被重写。

...

(混合) 构造方法中传入的其他所有参数用来当作每次请求的默认参数。

发送请求

Client对象的方法可以很容易的发送请求:

  1. $response = $client->get('http://httpbin.org/get');
  2. $response = $client->delete('http://httpbin.org/delete');
  3. $response = $client->head('http://httpbin.org/get');
  4. $response = $client->options('http://httpbin.org/get');
  5. $response = $client->patch('http://httpbin.org/patch');
  6. $response = $client->post('http://httpbin.org/post');
  7. $response = $client->put('http://httpbin.org/put');

你可以创建一个请求,一切就绪后将请求传送给client:

  1. use GuzzleHttp\Psr7\Request;
  2. $request = new Request('PUT', 'http://httpbin.org/put');
  3. $response = $client->send($request, ['timeout' => 2]);

Client对象为传输请求提供了非常灵活的处理器方式,包括请求参数、每次请求使用的中间件以及传送多个相关请求的基URI。

你可以在 Handlers and Middleware 页面找到更多关于中间件的内容。

异步请求

你可以使用Client提供的方法来创建异步请求:

  1. $promise = $client->getAsync('http://httpbin.org/get');
  2. $promise = $client->deleteAsync('http://httpbin.org/delete');
  3. $promise = $client->headAsync('http://httpbin.org/get');
  4. $promise = $client->optionsAsync('http://httpbin.org/get');
  5. $promise = $client->patchAsync('http://httpbin.org/patch');
  6. $promise = $client->postAsync('http://httpbin.org/post');
  7. $promise = $client->putAsync('http://httpbin.org/put');

你也可以使用Client的 sendAsync() and requestAsync() 方法:

  1. use GuzzleHttp\Psr7\Request;
  2. // Create a PSR-7 request object to send
  3. $headers = ['X-Foo' => 'Bar'];
  4. $body = 'Hello!';
  5. $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
  6. // Or, if you don't need to pass in a request instance:
  7. $promise = $client->requestAsync('GET', 'http://httpbin.org/get');

这些方法返回了Promise对象,该对象实现了由 Guzzle promises library 提供的 Promises/A+ spec ,这意味着你可以使用 then() 来调用返回值,成功使用 Psr\Http\Message\ResponseInterface 处理器,否则抛出一个异常。

  1. use Psr\Http\Message\ResponseInterface;
  2. use GuzzleHttp\Exception\RequestException;
  3. $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
  4. $promise->then(
  5. function (ResponseInterface $res) {
  6. echo $res->getStatusCode() . "\n";
  7. },
  8. function (RequestException $e) {
  9. echo $e->getMessage() . "\n";
  10. echo $e->getRequest()->getMethod();
  11. }
  12. );

并发请求

你可以使用Promise和异步请求来同时发送多个请求:

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Promise;
  3. $client = new Client(['base_uri' => 'http://httpbin.org/']);
  4. // Initiate each request but do not block
  5. $promises = [
  6. 'image' => $client->getAsync('/image'),
  7. 'png' => $client->getAsync('/image/png'),
  8. 'jpeg' => $client->getAsync('/image/jpeg'),
  9. 'webp' => $client->getAsync('/image/webp')
  10. ];
  11. // Wait on all of the requests to complete.
  12. $results = Promise\unwrap($promises);
  13. // You can access each result using the key provided to the unwrap
  14. // function.
  15. echo $results['image']->getHeader('Content-Length');
  16. echo $results['png']->getHeader('Content-Length');

当你想发送不确定数量的请求时,可以使用 GuzzleHttp\Pool 对象:

  1. use GuzzleHttp\Pool;
  2. use GuzzleHttp\Client;
  3. use GuzzleHttp\Psr7\Request;
  4. $client = new Client();
  5. $requests = function ($total) {
  6. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  7. for ($i = 0; $i < $total; $i++) {
  8. yield new Request('GET', $uri);
  9. }
  10. };
  11. $pool = new Pool($client, $requests(100), [
  12. 'concurrency' => 5,
  13. 'fulfilled' => function ($response, $index) {
  14. // this is delivered each successful response
  15. },
  16. 'rejected' => function ($reason, $index) {
  17. // this is delivered each failed request
  18. },
  19. ]);
  20. // Initiate the transfers and create a promise
  21. $promise = $pool->promise();
  22. // Force the pool of requests to complete.
  23. $promise->wait();