这是使用 zttp 去 post 一个自定义头部内容请求的一个例子:
$response = zttp::withheaders(['fancy' => 'pants'])->post($url, [ 'foo' => 'bar', 'baz' => 'qux', ]); $response->json();
如果用一个与 guzzle 差不多的东西写这个请求的话,大概这样写:
$client = new client(); $response = $client->request('post', $url, [ 'headers' => [ 'fancy' => 'pants', ], 'form_params' => [ 'foo' => 'bar', 'baz' => 'qux', ] ]); json_decode($response->getbody());
相较之下,zttp 简化了代码的写法,还能很简单地返回 json 格式的内容。
下面是 使用 zttp 的几个例子:
带参数的 post 请求#
$response = zttp::asformparams()->post($url, [ 'foo' => 'bar', 'baz' => 'qux', ]);
patch 请求#
$response = zttp::patch($this->url('/patch'), [ 'foo' => 'bar', 'baz' => 'qux', ]);
put 请求#
$response = zttp::put($this->url('/put'), [ 'foo' => 'bar', 'baz' => 'qux', ]);
delete 请求#
$response = zttp::delete($this->url('/delete'), [ 'foo' => 'bar', 'baz' => 'qux', ]);
添加请求头#
$response = zttp::accept('banana/sandwich')->post($url);
防止重定向#
$response = zttp::withoutredirecting()->get($url);
相关推荐:
php http 客户端和框架:guzzle
关于guzzle安装问题
laravel 怎么使用guzzlehttp/guzzle
以上就是zttp简化guzzle调用实例分享的详细内容。