2012-03-28 100 views
1
static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userp) 
    { 
     int totalSize = size*nmemb; 
     if(totalSize > 1) 
     { 
      strncpy((char*)userp,(char*)ptr,totalSize); 
     } 
     return totalSize; 
    } 

curl_easy_setopt(curl, CURLOPT_HEADER, 1L); 
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &this->responseData); 
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION ,write_callback); 

如何在write_callback函數中獲取頭響應和正文?如何在POST請求後使用curl獲取HTTP響應頭和主體

我必須打印像這樣的表格。

響應頭:200 體:誤差太大。

回答

3

如果使用curl_easy_setopt(curl, CURLOPT_HEADER, 1)你可以得到響應頭。

write_callback可稱爲多次

剛剛嘗試這一點。

curl_test.c

#include <stdio.h> 
#include <curl/curl.h> 
#include <stdlib.h> 
#include <unistd.h> 

size_t write_func(void *ptr, size_t size, size_t nmemb, void *userdata) 
{ 
     //write(STDOUT_FILENO, ptr, size*nmemb); 
     printf("write_func\n"); 
     return size * nmemb; 
} 

int main(int argv, char *argc[]) 
{ 
     CURL *curl; 
     if (argv != 2) { 
       return 0; 
     } 
     curl = curl_easy_init(); 
     if (!curl) { 
       fprintf(stderr, "curl_easy_init error"); 
     } 
     curl_easy_setopt(curl, CURLOPT_URL, argc[1]); 
     curl_easy_setopt(curl, CURLOPT_HEADER, 1); 
     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func); 
     curl_easy_perform(curl); 
     curl_easy_cleanup(curl); 
     return 0; 
} 

CMD:

gcc curl_test.c -o curl_test -lcurl && ./curl_test www.google.com 
相關問題