我可以在Guzzle的路由文件中指定Accept和Content-Type标头吗?

时间:2014-01-06 16:40:24

标签: php rest http-headers guzzle

我使用Guzzle向网络服务发出请求。

我的JSON文件看起来像这样:

{
    "name": "Webservice name",
    "apiVersion": "1.0",
    "description": "description",
    "operations": {
        "commandName1": {
            "httpMethod": "POST",
            "uri": "some/uri/to/some/resource/{value}",
            "summary": "description",
            "parameters": {
                "value": {
                    "location": "uri",
                    "description": "description"
                }
            }
        },
        "commandName2": {
            "httpMethod": "POST",
            "uri": "some/uri/to/some/resource/{value}",
            "summary": "description",
            "parameters": {
                "value": {
                    "location": "uri",
                    "description": "description"
                }
            }
        }
    }
}

并且使用它的代码看起来像这样:

$client = new Client(); // instance of Guzzle\Service\Client

$this->client->setDefaultOption(
    'auth',
    array('admin', 'admin', 'Basic')
);

$this->client->setDefaultOption(
    'headers',
    array('Accept' => 'text/html', 'Content-Type' => 'text/html')
);

$description = ServiceDescription::factory('/path/to/json/file/with/routes');
$client->setDescription($description);

$params = array(
    'command.request_options' = array(
        'timeout'         => 5,
        'connect_timeout' => 2
    )
);

$command = $client->getCommand('commandName1', $params);
$command->prepare();

$client->execute($command);

如您所见,我在PHP代码中指定了Content-TypeAccept标头。有什么方法可以在JSON文件中移动该信息并为每个操作指定不同的值?例如:我希望“commandName1”将HTML作为内容类型,但是“commandName2”具有JSON。

我想这样做是为了避免大量的代码重复。

过去2小时我一直在网上和Guzzle的文档中查看并且空了。但是,在我看来,文档有点写得不好 1 ,我在阅读时确实错过了一些东西。所以它很有可能再次发生。

有没有人曾经做过这样的事情?你是怎么解决的?提前谢谢。

1 =“写得不好”我实际上意味着每个部分都是不完整的。每一章似乎都触及一个主题,但绝不提供实际的完整或深入的参数,方法等描述或其全部功能。 NO CODE SNIPPET SSCCE,因此您可以在不到2分钟的复制粘贴中看到它在您眼前工作。但这是另一个主题......

1 个答案:

答案 0 :(得分:5)

我查看了Guzzle的源代码,实际上没有办法将这些信息添加到JSON文件中。

但是我成功地改变了这个:

$params = array(
    'command.request_options' = array(
        'timeout'         => 5,
        'connect_timeout' => 2
    )
);

到此:

$params = array(
    'command.request_options' => array(
        'timeout'         => 5,
        'connect_timeout' => 2
    ),
    'command.headers' => array(
        'Accept'        => 'whatever value I want',
        'Content-Type'  => 'whatever value I want'
    )
);

并且有效。

由于代码的这一部分位于每个其他类使用的单独/公共类中,因此没有代码重复,因此它可以工作......有点。