【问题标题】:Can I specify Accept and Content-Type headers in Guzzle's routes file?我可以在 Guzzle 的路由文件中指定 Accept 和 Content-Type 标头吗?
【发布时间】:2014-01-24 03:21:19
【问题描述】:

我使用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 SNIPPETSSCCE,因此您可以在不到 2 分钟的复制粘贴时间中看到它在您眼前工作。不过这是另外一个话题了……

【问题讨论】:

  • 同意写得不好的文档...

标签: php rest http-headers guzzle


【解决方案1】:

我查看了 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'
    )
);

它成功了。

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

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2016-06-24
    • 2012-04-29
    • 2012-07-08
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多