理解HTTP協議中的”Transfer-Encoding: chunked”

來源:互聯網
上載者:User
 最近寫個http用戶端的小程式,由於http是基於tcp的無訊息邊界保護的協議,所以接受時必須要確定接受資料的數量才能完整接收資料。傳統的方式,只要先接收到Content-Length就可以通過這個長度接受訊息體部分了。而transfer-encoding:chunked的引入,打破了這個規矩,正好找到一篇合適的文章,轉載之。 轉自:http://hi.baidu.com/ah__fu/blog/item/c3d47b2f0bcd65301e30891e.html  
    通常,HTTP協議中使用Content-Length這個頭來告知資料的長度。然後,在資料下行的過程中,Content-Length的方式要預先在伺服器中緩衝所有資料,然後所有資料再一股腦兒地發給用戶端。
    如果要一邊產生資料,一邊發給用戶端,WEB 伺服器就需要使用"Transfer-Encoding: chunked"這樣的方式來代替Content-Length。

    "Transfer-Encoding: chunked"是這樣編碼的:
HTTP頭
\r\n
\r\n      --連續的兩個\r\n之後就是HTTP體了
16進位值代表的資料長度
\r\n
上面所指的資料長度
\r\n    --每段資料結束後,以\r\n標識

16進位代表的第二段資料
\r\n
XX長度的資料
\r\n

………… (反覆通過這樣的方式表示每次傳輸的資料長度)

0      --資料結束部分用0表示,然後是連續的兩個\r\n
\r\n
\r\n

      下面的代碼示範和如何解析"Transfer-Encoding: chunked"的資料:
//test_chunked.cpp
#include <stdio.h>
#include <string.h>

int Hex2Int(const char* str)
{
    int nResult = 0;
    while (*str!='\0')
    {
        switch (*str)
        {
        case '0'...'9':
            nResult = nResult*16 + *str-'0';
            break;
        case 'a'...'f':
            nResult = nResult*16 + *str-'a'+10;
            break;
        case 'A'...'F':
            nResult = nResult*16 + *str-'A'+10;
            break;
        default:
            return -1;
            break;
        }
        str++;
    }
    return nResult;
}

#define COPY_STRING(dst, src, src_len) do{memcpy((dst), (src), (src_len)); dst[(src_len)]='\0';}while(0);

void test(const char* file)
{
    //
    const int BUFFER_SIZE = 1024*10;
    char* buf = new char[BUFFER_SIZE];
    FILE* fp = fopen(file, "rb");
    if (NULL==fp)
    {
        printf("open file error\n");
        return;
    }
    int nLen = fread(buf, 1, BUFFER_SIZE, fp);
    fclose(fp);
    fp = NULL;
    buf[nLen] = '\0';
    //
    char* pBody = strstr(buf, "\r\n\r\n");
    if (NULL==pBody)
    {
        return;
    }
    pBody += 4;
    FILE* fDst = fopen("result.txt.gz", "ab");
    //下面開始解析
    int nBytes;
    char* pStart = pBody;
    char* pTemp;
    char temp[10];
    do
    {
        pTemp = strchr(pStart, '\r');
        if (NULL==pTemp)
        {
            printf("格式錯誤!\n");
            break;
        }
        nLen = pTemp-pStart;
        COPY_STRING(temp, pStart, nLen);
        nBytes = Hex2Int(temp);
        pStart = pTemp + 2;
        //下面寫入到另一個檔案
        if (nBytes>0)
        {
            if (nBytes!=fwrite(pStart, 1, nBytes, fDst))
            {
                printf("write error!\n");
                break;
            }
            pStart += nBytes + 2;
        }
    } while(nBytes>0);
    fclose(fDst);
    fDst = NULL;
    delete[] buf;
    buf = NULL;
}

int main()
{
    test("chunked.txt");
    return 1;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.