无法使用guzzle服务向我的请求添加授权标头

时间:2014-08-03 20:31:07

标签: php guzzle

我有以下代码:

Client class


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

     class ApiClient extends Client
     {
       public static function factory($config = array())
       {
        $config = array_merge($config, json_decode(file_get_contents(__DIR__.'/Resources/config/client.json'), TRUE));

        $guzzleClient = new GuzzleClient(new Client(), new Description($config));

        return $guzzleClient;
    }
}

配置设置

   {
    "operations": {
        "me":{
            "description": "Returns user profile details",
            "httpMethod": "GET",
            "uri": "users/me",
            "parameters": {
                "token": {
                    "type":"string",
                    "location": "header",
                    "sentAs": "Authorization"
                }
            }
        }
    }
}

```

用法

$config = [
    'baseUrl' => 'http://localhost/api/v1/'
];
$api_client = ApiClient::factory($config);

$token   = 'Bearer V6tBMG6FKL7wLxZh116IGdvfDUtOvlFIJI61nrHp';
$command = $api_client->me(array(
    'token' => $token
));

// returns an array of results
$results = $command->execute();

我想为所有请求添加自定义Autorizarion Bearer标头,我该怎么做?将标题添加到$ client并且在call me方法为NULL后帮助cuz $命令。

由于

已更新

发现错误,它不起作用cuz guzzle 4配置以不同的方式工作:

{
    "operations": {
        "me":{
            "description": "Return solidoptics user profile details",
            "httpMethod": "GET",
            "uri": "users/me",
            "responseModel": "getResponse",
            "parameters": {
                "token": {
                    "type":"string",
                    "location": "header",
                    "sentAs": "Authorization",
                    "required": true
                }
            }
        }
    },
    "models": {
        "getResponse": {
            "type": "object",
            "additionalProperties": {
                "location": "json"
            }
        }
    }
}

所以现在问题不适合我。

2 个答案:

答案 0 :(得分:0)

尝试为客户端配置default request options,执行以下操作:

$client = new Client(array(
    'defaults' => array(
        'headers' => array(
            'Authorization' => '...',
         ),
    ),
));

并确保在致电$client时使用new Client(),而不是new GuzzleClient

答案 1 :(得分:0)

您可以添加新的配置数组

$clientConfig['defaults']['token'] = $token;

并将该配置作为第三个参数传递给 new GuzzleHttp\Command\Guzzle\GuzzleClient。 这些默认值将在命令创建时复制到命令参数中。

您还可以修改Description对象中的默认值。

您还可以在GuzzleHttp\Client配置中设置默认值。