解码 HTTP 分块 +压缩内容
如何解码服务器响应
1) 传输编码:分块 2)内容类型:gzip
我需要手动执行此操作,不能仅使用curl来发送请求。我需要从原始 $string 进行解码。
这是一个应该对 HTTP 响应进行分块的函数 (php):
function unchunkHttpResponse($str=null) {
if (!is_string($str) or strlen($str) < 1) { return false; }
$eol = "\r\n";
$add = strlen($eol);
$tmp = $str;
$str = '';
do {
$tmp = ltrim($tmp);
$pos = strpos($tmp, $eol);
if ($pos === false) { return false; }
$len = hexdec(substr($tmp,0,$pos));
if (!is_numeric($len) or $len < 0) { return false; }
$str .= substr($tmp, ($pos + $add), $len);
$tmp = substr($tmp, ($len + $pos + $add));
$check = trim($tmp);
} while(!empty($check));
unset($tmp);
return $str;
}
但它似乎不适用于 gzip 压缩的内容(gzinflate 不在这个代码片段中)。我尝试对返回的内容执行 gzinflate 但这根本不起作用。
有什么想法吗?或者 gzip + 传输编码分块如何协同工作?
谢谢
How would one decode a server response that is
1) transfer-encode: chunked
2) content-type: gzip
I need to do this manually and can't just use curl to send the request. I need to decode from the raw $string.
Here's a function that is supposed to unchunk a HTTP reponse (php):
function unchunkHttpResponse($str=null) {
if (!is_string($str) or strlen($str) < 1) { return false; }
$eol = "\r\n";
$add = strlen($eol);
$tmp = $str;
$str = '';
do {
$tmp = ltrim($tmp);
$pos = strpos($tmp, $eol);
if ($pos === false) { return false; }
$len = hexdec(substr($tmp,0,$pos));
if (!is_numeric($len) or $len < 0) { return false; }
$str .= substr($tmp, ($pos + $add), $len);
$tmp = substr($tmp, ($len + $pos + $add));
$check = trim($tmp);
} while(!empty($check));
unset($tmp);
return $str;
}
But it seems to not work with gzipped content (gzinflate is not in this snippet). I tried doing gzinflate on the returned content but that doesn't work at all.
Any ideas? Or how do gzip + transfer encoding chunked work together?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您能否首先通过尝试针对某些文本响应来验证此函数是否确实正确聚合了分块响应。我不精通 php,所以我不能确定这个函数是否有效,但由于 gzipped 响应将是二进制的,我想知道将它连接到字符串是否可以。您能解释一下为什么需要“从原始 $string 解码”吗?为什么使用一些被证明可以正确处理所有 HTTP 详细信息的客户端,并夸大它返回的任何内容对您不起作用?
Could you start by verifying that this function indeed properly aggregates chunked response by trying it against some text response. I'm not proficient in php so I can't say for sure if this function will work, but as gzipped response will be binary, I wonder if concatenating it to string is OK thing to do. And could you explain why you need to "decode from the raw $string"? Why using some client that is proven to handle all HTTP details properly, and inflating whatever it returns is not working for you?