How to get HTTP response headers and body after POST request using curl

http, http-headers, http-post, libcurl
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);

how to get header response and body in write_callback function ?

I have to print like this form.

response header : 200
body : error-too big.

Best Solution

You can get response header if you use curl_easy_setopt(curl, CURLOPT_HEADER, 1).

But the write_callback may be called many times

Just try this.

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