解码 HTTP 分块 +压缩内容

发布于 2024-12-09 11:50:13 字数 841 浏览 0 评论 0原文

如何解码服务器响应

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南风起 2024-12-16 11:50:13

您能否首先通过尝试针对某些文本响应来验证此函数是否确实正确聚合了分块响应。我不精通 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文