大连249建站之家免费精品网站自助建设系统平台免费微
首页 >> 技术分享 >>技术干货 >> 249建站之家:一个基于 Guzzle Http 的更好用的 PHP HTTP Package
详细内容

249建站之家:一个基于 Guzzle Http 的更好用的 PHP HTTP Package

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

大致来看看 Zttp 的用法:

1.比如发送一个携带 headers 的 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 还是方便,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.

联系我们
更多

联系电话:0411-66373325

联系地址:大连市沙河口区富民广场

公司邮箱:2058793689@qq.com

备案信息:Copyright © 2016-2025,www.my249.com,All rights reserved

辽ICP备17015910号-1

seo seo