2011-12-06 15 views
7

Sto cercando di analizzare la seguente risposta HTTP:C principianti: stringa parsing

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 

Voglio estrarre "48" e il contenuto binario.

Ecco che cosa ho provato 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"); 
    } 

Ma io sono un po 'bloccato ormai ... Ogni aiuto è molto apprezzato.


edit:

Ecco quello che ho fatto sofar:

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

Come posso ottenere la punta tra questi due puntatori?


Edit: Soluzione:

 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

Puoi controllare http://curl.haxx.se/libcurl/c/ e l'opzione 'CURLOPT_WRITEHEADER' – Cyclonecode

+0

Voglio evitare di usare CURL. Sto facendo tutto usando le prese ... – Eamorr

risposta

6

Perché non invece cercare la stringa "Content-Length:"? poi da quel punto si muove in avanti.

È possibile utilizzare strstr() per trovare il punto in str, quindi spostare il puntatore char avanti strlen ("Content-Length:") posizioni, quindi leggere il valore utilizzando atoi()

non v'è alcuna necessità di tokenize l'intera stringa

+0

Grazie per quello. Ho aggiornato l'OP. – Eamorr

2

Prova questo:

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

Ovviamente dovresti controllare che pdata e pcontent siano validi prima di usarli – Cyclonecode

+0

... e sperare che nessuno metta "Content-Length: -1" nella loro stringa Server? – caf

+0

No, si spera non sia =) – Cyclonecode