出于某种原因,当我发送新的$ client->请求时,我指定的标头会丢失:
public function testGetClientsAction()
{
$client = static::createClient();
$cookie = new Cookie('locale2', 'en', time() + 3600 * 24 * 7, '/', null, false, false);
$client->getCookieJar()->set($cookie);
// Visit user login page and login
$crawler = $client->request('GET', '/login');
$form = $crawler->selectButton('login')->form();
$crawler = $client->submit($form, array('_username' => 'greg', '_password' => 'greg'));
$client->request(
'GET',
'/clients',
array(),
array(),
array('X-Requested-With' => 'XMLHttpRequest', 'accept' => 'application/json')
);
print_r($client->getResponse());
die();
}
在正在测试的方法中,我在第一行有这个:
print_r($request->headers->all());
回复如下:
Array
(
[host] => Array
(
[0] => localhost
)
[user-agent] => Array
(
[0] => Symfony2 BrowserKit
)
[accept] => Array
(
[0] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
)
[accept-language] => Array
(
[0] => en-us,en;q=0.5
)
[accept-charset] => Array
(
[0] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
)
[referer] => Array
(
[0] => http://localhost/login_check
)
[x-php-ob-level] => Array
(
[0] => 1
)
)
答案 0 :(得分:46)
我有同样的问题,经过一番挖掘,我认为这是BrowserKit目前不支持的功能。
我已经为它记录了一个问题: https://github.com/symfony/symfony/issues/5074
更新:这不是问题 - 请参阅下面的评论
样品申请:
$client->request(
'GET',
$url,
array(),
array(),
array(
'HTTP_X_CUSTOM_VAR' => $var
)
);
获取数据:
$request->headers->get('x-custom-var');
答案 1 :(得分:4)
如果从Client.php检查定义,则在方法请求中,您将在docblock中看到一个非常有用的信息:
这意味着您应该在要发送的标头中添加 HTTP _ 前缀。例如,如果要传递标题X-HTTP-Method-Override,请按以下方式指定它:
$client->request(
Request::METHOD_POST,
'/api/v1/something',
$body,
[],
['HTTP_X-HTTP-Method-Override' => Request::METHOD_GET]
);