---
title: "HTTP协议--关于Chunked编码"
author: "soardragon"
date: "2007-06-25T17:50:31Z"
tags: []
slug: "http-chunked"
draft: false
lastmod: "2007-06-25T17:50:31Z"
id: 94045
url: "https://library.iteye.com/blog/94045"
---

在有时服务器生成HTTP回应是无法确定消息大小的，这时用Content-Length就无法事先写入长度，而需要实时生成消息长度，这时服务器一般采用Chunked编码。  
　　在进行Chunked编码传输时，在回复消息的头部有transfer-coding并定为Chunked，表示将用Chunked编码传输内容。采用以下方式编码：  
　　Chunked-Body=\*chunk  
　　　　　　　　　"0"CRLF  
　　　　　　　　　footer  
　　　　　　　　　CRLF  
　　chunk=chunk-size\[chunk-ext]CRLF  
　　　　　　chunk-dataCRLF

　　hex-no-zero=&lt;HEXexcluding"0"&gt;

　　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  
　　编码使用若干个Chunk组成，由一个标明长度为0的chunk结束，每个Chunk有两部分组成，第一部分是该Chunk的长度和长度单位（一般不写），第二部分就是指定长度的内容，每个部分用CRLF隔开。在最后一个长度为0的Chunk中的内容是称为footer的内容，是一些没有写的头部内容。  
　　下面给出一个Chunked的解码过程（RFC文档中有）  
　　length:=0  
　　readchunk-size,chunk-ext(ifany)andCRLF  
　　while(chunk-size&gt;0){  
　　readchunk-dataandCRLF  
　　appendchunk-datatoentity-body  
　　length:=length+chunk-size  
　　readchunk-sizeandCRLF  
　　}  
　　readentity-header  
　　while(entity-headernotempty){  
　　appendentity-headertoexistingheaderfields  
　　readentity-header  
　　}  
　　Content-Length:=length  
　　Remove"chunked"fromTransfer-Encoding  
　　下一次将会讨论一些小问题，如POST方法的数据传输等。  
　　最后，还有一点要说的是，好像NetAnt的一个版本不支持Chunked编码，会显示无法确定内容长度，或许是版本太低的缘故，如果你也遇到这种问题，可以改用NetVampire或其它支持Chunked编码的下载程序试试。