c语言中使用curl

 

#include <stdio.h>
#include <curl/curl.h>
#include <lauxlib.h>

// 回调函数,用于处理响应数据
size_t write_callback(void *contents, size_t size, size_t nmemb, char **response) {
    printf("write_callback begin: %d, %d\n", size, nmemb);

    //size:每数据块大小, nmemb:数据块个数
    size_t totalSize = size * nmemb;
    *response = realloc(*response, strlen(*response) + totalSize + 1);
    if (*response == NULL) {
        fprintf(stderr, "Failed to allocate memory\n");
        return 0;
    }
    strncat(*response, (char*)contents, totalSize);

    printf("write_callback end\n");
    return totalSize;
}

int main() {
    curl_global_init(CURL_GLOBAL_ALL); /* In windows, this will init the winsock stuff */
    CURL *curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, "http://httpbin.org/get");

    // 设置请求头
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    char *response = calloc(1, 1);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); //指针变量的地址作为userData
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

    CURLcode code = curl_easy_perform(curl);
    if (code != CURLE_OK) {
        printf("err: %d, %s\n", code, curl_easy_strerror(code));
    }
    else {
        long http_code = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
        printf("HTTP status code: %ld\n", http_code);
        printf("response: %s\n", response);
    }
    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    free(response);


    char c;
        scanf("%c", &c);
    return 0;
}

运行结果

 

参考

c语言实现一个简易的curl工具 - BrianSun - 博客园

 

posted @ 2025-07-05 08:38  yanghui01  阅读(21)  评论(0)    收藏  举报