我必须进行HTTP调用才能发送数据压缩数据。我正在Symfony2中开发。对于HTTP调用,我使用的是Guzzle客户端(版本3.8.1)。此外,我正在使用 Guzzle 服务描述来描述每个命令允许的操作。
我知道我必须在请求中添加标头"内容编码:gzip",但请求正文未压缩。
有没有办法在 Guzzle 客户端中指定请求需要压缩?(也许在服务说明中指定)
谢谢!
要告诉服务器给你压缩版本,你必须通知它你知道如何解压缩数据。
为此,您在请求期间发送一个标头,称为Accept-Encoding
。
accept-encoding
标头和值的示例(这些是客户端知道使用的压缩方案):
accept-encoding:gzip, deflate, sdch, br
响应标头Content-Encoding
由服务器发送。如果设置了该标头,则客户端断言内容已压缩,并使用服务器发送的算法作为值Content-Encoding
。
服务器不必使用压缩页面进行响应。
因此,这些是步骤:
告诉服务器您知道如何处理压缩页面。发送
accept-encoding
标头,然后指定客户端知道如何处理的压缩算法。检查服务器是否发送了
Content-Encoding
标头。否则,不会压缩内容如果是,请检查标头的值。这告诉你哪种算法用于压缩,它不一定是gzip,但通常是。
服务器不必使用压缩页面进行响应。您只是通知服务器您了解如何处理压缩页面。
因此,对您来说,您应该做的是验证您的服务器是否发送了 gzip 响应,然后您应该将请求标头设置为accept-encoding
。你弄错了。
我找到了一个解决方案,可以使用带有操作命令和服务描述的 Guzzle 客户端发送压缩的数据。
在包含服务描述的 JSON 文件中,我指定在正文中发送的数据是一个字符串:
{
...
"operations": {
"sendCompressedData": {
"httpMethod": "POST",
"uri": ...,
"parameters": {
"Content-Type": {
"location": "header",
"required": true,
"type": "string",
"default": "application/json"
},
"Content-Encoding": {
"location": "header",
"required": true,
"type": "string",
"default": "gzip"
},
"data": {
"location": "body",
"required": true,
"type": "string"
}
}
}
}
}
正如@Mjh所提到的,如果设置了"内容编码"标头,Guzzle 不会自动压缩数据,因此在将数据发送到 Guzzle 客户端以执行命令之前,需要压缩数据。我已经序列化了对象并使用"gzencode($string)"进行压缩。
$serializedData = SerializerBuilder::create()->build()->serialize($request, 'json');
$compressedData = gzencode($serializedData);
...
$command = $this->client->getCommand('sendCompressedData', array('data' => $compressedData));
$result = $command->execute();