如何在使用curl的POST请求后获取HTTP响应头和正文

时间:2012-03-28 08:52:32

标签: 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);

如何在write_callback函数中获取头响应和body?

我必须像这样的表格打印。

响应标题:200 身体:错误 - 太大了。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

要按照您想做的官方 libcurl 指南进行操作:

/* send all data to this function  */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, cb);

/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);

与:

struct memory {
    char *response;
    size_t size;
};

static size_t cb(void *data, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    struct memory *mem = (struct memory *)userp;

    char *ptr = realloc(mem->response, mem->size + realsize + 1);
    if(ptr == NULL)
        return 0;  /* out of memory! */

    mem->response = ptr;
    memcpy(&(mem->response[mem->size]), data, realsize);
    mem->size += realsize;
    mem->response[mem->size] = 0;

    return realsize;
}

struct memory chunk;

参考:https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html