Guzzle - Command&服务:基本HTTP身份验证

时间:2016-07-13 19:17:15

标签: php web-services rest guzzle guzzle6

我之前已成功使用guzzlehttp/guzzle v.6.*包和身份验证参数,如下所示:

        $client = new GuzzleClient([
            'base_uri'  => $base_uri ,
            'auth'      => [ $username, $password ]
        ]);

这很有效。但是,我现在正尝试使用"guzzlehttp/guzzle-services": "0.5.*"包来更轻松地使用API​​端点。

使用guzzle-services' Github page中的以下示例:

use GuzzleHttp\Client;
use GuzzleHttp\Command\Guzzle\GuzzleClient;
use GuzzleHttp\Command\Guzzle\Description;

$client = new Client();
$description = new Description([
    'baseUrl' => 'http://httpbin.org/',
    'operations' => [
        'testing' => [
            'httpMethod' => 'GET',
            'uri' => '/get/{foo}',
            'responseModel' => 'getResponse',
            'parameters' => [
                'foo' => [
                    'type' => 'string',
                    'location' => 'uri'
                ],
                'bar' => [
                    'type' => 'string',
                    'location' => 'query'
                ]
            ]
        ]
    ],
    'models' => [
        'getResponse' => [
            'type' => 'object',
            'additionalProperties' => [
                'location' => 'json'
            ]
        ]
    ]
]);

$guzzleClient = new GuzzleClient($client, $description);
$result = $guzzleClient->testing(['foo' => 'bar']);

在使用"guzzlehttp/guzzle-services": "0.5.*"包时,我在世界上如何以及在何处添加身份验证参数?

我已尽力尝试各种方法,但无法让它发挥作用。

2 个答案:

答案 0 :(得分:1)

我已成功使用Guzzle 6.2.2和Guzzle Services 1.0.0与Basic Auth一起使用此代码:

$config['auth'] = array('user', 'pass');
$client = new Client($config);

当然,您可能需要其他设置,但对于Basic Auth,只需要这样做。检查GuzzleHttp\Client::applyOptions类方法以查看Guzzle何时使用此设置。

它与@revo答案非常相似,但没有主要的'默认'数组。

这些是我的guzzle安装包:

"
gimler/guzzle-description-loader     v0.0.2  Load guzzle service description from various file formats
guzzlehttp/command                   1.0.0   Provides the foundation for building command-based web service clients
guzzlehttp/guzzle                    6.2.2   Guzzle is a PHP HTTP client library
guzzlehttp/guzzle-services           1.0.0   Provides an implementation of the Guzzle Command library that uses Guzzle service descriptions to describe web services, se...
guzzlehttp/promises                  1.3.0   Guzzle promises library
guzzlehttp/psr7                      1.3.1   PSR-7 message implementation
"

答案 1 :(得分:0)

我怀疑Client类是否提供了将身份验证信息合并到请求的方法。但是你可以在Guzzle v5.x中实例化一个新的$client = new Client(['defaults' => ['auth' => ['user', 'pass']]]); 时添加它们,如下所示:

class2 *obj = 0;
void class1::function1()
{
    if(!obj)
    {
        obj = new class2();
        connect(this, SIGNAL(sig()), obj, SLOT(slt()));
    }
}

void class2::function2()
{
    emit sig();
}