2011-12-06 61 views
7

我試圖解析以下HTTP響應:Ç初學者:字符串解析

HTTP/1.1 200 OK 
Date: Tue, 06 Dec 2011 11:15:21 GMT 
Server: Apache/2.2.14 (Ubuntu) 
X-Powered-By: PHP/5.3.2-1ubuntu4.9 
Vary: Accept-Encoding 
Content-Encoding: gzip 
Content-Length: 48 
Content-Type: text/html 

��(�ͱ���I�O����H�����ч�� 
         �4�@�B�$���S 

我想提取「48」和二進制內容。

這裏就是我試過SOFAR:

//char* str contains the response 
    char * pch; 
    printf ("Splitting response into tokens:\n"); 
    pch = strtok (str,"\r\n"); 
    while (pch != NULL) 
    { 
     printf ("%s\n",pch); 
     pch = strtok (NULL, "\r\n"); 
    } 

但我現在有點粘...任何幫助是極大的讚賞。


編輯:

這裏就是我做SOFAR:

char* pch; 
char* pch2; 
pch=strstr(buf,"Content-Length:"); 
pch2=strstr(pch,"\r\n"); 

我怎樣才能得到這兩個指針之間的位?


編輯:解:

 char* pch; 
     char* pch2; 
     pch=strstr(buf,"Content-Length:"); 
     int i=0; 
     char contLen[20]; 
     for(i=0;i<20;i++){ 
       char next=pch[strlen("Content-Length:")+i]; 
       if(next=='\r' || next=='\n'){ 
         break; 
       } 
       contLen[i]=next; 
     } 
     printf("%d\n",atoi(contLen)); 
+0

你可以檢查http://curl.haxx.se/libcurl/c/和'CURLOPT_WRITEHEADER'選項 – Cyclonecode

+0

我想避免使用捲曲。我正在做一切使用套接字... – Eamorr

回答

6

你爲什麼不改爲搜索字符串"Content-Length:"?那麼從那一點開始向前邁進。

您可以使用的strstr()找到STR現場,然後將字符指針向前的strlen( 「內容長度:」)位置,然後閱讀使用的atoi()的值

沒有必要來標記整個字符串

+0

謝謝你。我已經更新了OP。 – Eamorr

2

試試這個:

const char* http_header = 
"HTTP/1.1 200 OK\r\n" \ 
"Date: Tue, 06 Dec 2011 11:15:21 GMT" \ 
"Server: Apache/2.2.14 (Ubuntu)\r\n" \ 
"X-Powered-By: PHP/5.3.2-1ubuntu4.9\r\n" \ 
"Vary: Accept-Encoding\r\n" \ 
"Content-Encoding: gzip\r\n" \ 
"Content-Length: 48\r\n" \ 
"Content-Type: text/html\r\n\r\n" \ 
"mydata"; 

// will point to start of data 
char* pdata = strstr((char*)http_header,"\r\n\r\n"); 
    // will point to start of 'Content-Length' header 
char* pcontent = strstr((char*)http_header,"Content-Length:"); 
    // get the length of the data 
int value = atoi(pcontent+15); 
+0

當然,你應該檢查,以便PDATA和pcontent使用它們 – Cyclonecode

+0

之前是有效的......希望沒有人提出「內容長度:-1」到他們的服務器字符串? – caf

+0

沒有希望不是=) – Cyclonecode