Zttp - 一个基于 Guzzle Http 的更好用的 PHP HTTP Package

栏目: PHP · 发布时间: 6年前

内容简介:Zttp - 一个基于 Guzzle Http 的更好用的 PHP HTTP Package

原文: https://www.laravist.com/blog...

PHP 的项目中,如果你需要通过代码来发起 HTTP 请求,相信很多人对 GuzzleHttp 这个 Package 很熟悉,然而其实在使用 Guzzle 的时候,我们依然可以做得更简便一点的,比如我们可以使用 Zttp ,这是基于 Guzzle 的另外一个 HTTP Package。

大致来看看 Zttp 的用法:

1.比如发送一个携带 headersPOST 请求:

$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 还是方便,Nice and clean!

2.携带 Form 表单参数的 POST 请求:

$response = Zttp::asFormParams()->post($url, [
    'foo' => 'bar',
    'baz' => 'qux',
]);

3.发起 Patch 请求:

$response = Zttp::patch($this->url('/patch'), [
    'foo' => 'bar',
    'baz' => 'qux',
]);

4.发起 PUT 请求:

$response = Zttp::put($this->url('/put'), [
    'foo' => 'bar',
    'baz' => 'qux',
]);

5.发起 DELETE 请求:

$response = Zttp::delete($this->url('/delete'), [
    'foo' => 'bar',
    'baz' => 'qux',
]);

6.添加一个可接受的 Header:

$response = Zttp::accept('banana/sandwich')->post($url);

7.阻止重定向:

$response = Zttp::withoutRedirecting()->get($url);

你可以看到,上面的这些事例代码其实可以包含了大部分的应用场景,如果说你还需要更复杂的使用方式,你可以到 Github kitetail/zttp 查看;而且,即使你还想使用 Guzzle,你依然是可以使用 Guzzle 的,所以我可以负责任地向大家推荐一下这个 Zttp 的 package.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Persuasive Technology

Persuasive Technology

B.J. Fogg / Morgan Kaufmann / 2002-12 / USD 39.95

Can computers change what you think and do? Can they motivate you to stop smoking, persuade you to buy insurance, or convince you to join the Army? "Yes, they can," says Dr. B.J. Fogg, directo......一起来看看 《Persuasive Technology》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试