Rest 如何在ZendFramework2中发送PUT请求?

Rest 如何在ZendFramework2中发送PUT请求?,rest,zend-framework2,Rest,Zend Framework2,我试图弄清楚如何在PUT请求中发送参数。我有一个javascript界面,它工作得很好,所以我知道服务器端可以工作,但我的单元测试从未正确发送PUT参数。以下是我尝试过的: $this->request->getQuery()->set("id", $id); $params = array( 'attribute' => 'email', 'email' => 'new_email@email.com', ); // Set the

我试图弄清楚如何在PUT请求中发送参数。我有一个javascript界面,它工作得很好,所以我知道服务器端可以工作,但我的单元测试从未正确发送PUT参数。以下是我尝试过的:

$this->request->getQuery()->set("id", $id);
$params = array(
        'attribute' => 'email',
        'email' => 'new_email@email.com',
);
// Set the data to be validated
$this->request->setMethod('PUT');

// Send the additional parameters
$this->request->setContent(json_encode($params));
这是错误的,因为服务器正在查找$params key“attribute”,但服务器上的$params数组为空—没有传入任何$params。我尝试的时候也是一样

foreach ($params as $n => $v) {
    $this->routeMatch->setParam($n, $v);
}


在zf2中发送PUT参数的正确方法是什么?

解决方案是将
内容类型
标题设置为
应用程序/json
。然后

$this->request->setContent(json_encode($params));

工作。唯一的问题是它破坏了我所有的POST请求,这些请求都使用了
getPost()->set($n,$v)
。我必须回到每个测试中,对它们执行相同的setContent,然后它们也通过了。

要添加标题,请使用以下代码
$headers=newheaders()$headers->addHeaderLine('Content-type','application/json')$此->请求->设置标题($headers)
您可以使用
$this->request->getPost()->fromArray
而不是foreach循环来复制数组
foreach ($params as $n => $v) {
    $this->request->getPost()->set($n, $v);
}
$this->request->setContent(json_encode($params));