进行Chunked编码传输的HTTP Response会在消息头部设置: Transfer-Encoding: chunked 表示Content Body将用Chunked编码传输内容。 Chunked编码使用若干个Chunk串连而成,由一个标明长度为0的chunk标示结束。每个Chunk分为头部和正文两部分,头部内容指定下一段正文的字符总数(十六进制的数字)和数量单位(一般不写),正文部分就是指定长度的实际内容,两部分之间用回车换行(CRLF)隔开。在最后一个长度为0的Chunk中的内容是称为footer的内容,是一些附加的Header信息(通常可以直接忽略)。具体的Chunk编码格式如下: <div class="codetitle"><a style="CURSOR: pointer" data="55852" class="copybut" id="copybut55852" onclick="doCopy('code55852')"> 代码如下:<div class="codebody" id="code55852"> Chunked-Body = chunk "0" CRLF footer CRLF chunk = chunk-size [ chunk-ext ] CRLF chunk-data CRLF hex-no-zero = <HEX excluding "0"> chunk-size = hex-no-zero HEX chunk-ext = ( ";" chunk-ext-name [ "=" chunk-ext-value ] ) chunk-ext-name = token chunk-ext-val = token | quoted-string chunk-data = chunk-size(OCTET) footer = entity-header
RFC文档中的Chunked解码过程如下: <div class="codetitle"><a style="CURSOR: pointer" data="47566" class="copybut" id="copybut47566" onclick="doCopy('code47566')"> 代码如下:<div class="codebody" id="code47566"> length := 0 read chunk-size,chunk-ext (if any) and CRLF while (chunk-size > 0) { read chunk-data and CRLF append chunk-data to entity-body length := length + chunk-size read chunk-size and CRLF } read entity-header while (entity-header not empty) { append entity-header to existing header fields read entity-header } Content-Length := length Remove "chunked" from Transfer-Encoding
最后提供一段PHP版本的chunked解码代码: <div class="codetitle"><a style="CURSOR: pointer" data="25540" class="copybut" id="copybut25540" onclick="doCopy('code25540')"> 代码如下:<div class="codebody" id="code25540"> $chunk_size = (integer)hexdec(fgets( $socket_fd,4096 ) ); while(!feof($socket_fd) && $chunk_size > 0) { $bodyContent .= fread( $socket_fd,$chunk_size ); fread( $socket_fd,2 ); // skip rn $chunk_size = (integer)hexdec(fgets( $socket_fd,4096 ) ); }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|