libcurl用法/函数返回字符串

cooolr 于 2022-03-28 发布
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

size_t write_func(void *buffer, size_t size, size_t nmemb, void *user_ptr) {
    // 复制文本
    strcat(user_ptr, buffer);
    return size*nmemb;
}

char * get(char *url, char *body) {
    // 实例化curl
    CURL *curl = curl_easy_init();
    // 设置handle属性(url、回调函数、结果保存)
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_func);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, body);
    // 执行数据请求
    curl_easy_perform(curl);
    // 释放资源
    curl_easy_cleanup(curl);
    // printf("%s", body);
    return body;
}

int main() {
    char body[10240];
    get("http://httpbin.org/get", body);
    printf("%s", body);
    return 0;
}

编译

gcc test.c -lcurl