在C中重用curl easy handle

时间:2016-02-22 15:05:55

标签: c curl libcurl

在C项目中,我想重用curl easy handle。程序流程如下:

客户 - > C申请 - >调用URL1,做某事,调用URL2,做某事,调用URL3 ......

简而言之,对于每个客户端请求,都会调用相同的URL集。

我最初在程序启动时创建了curl easy handle。主程序创建一个可配置数量的子程序,因此每个子程序都可以轻松处理。

static int child_init(int rank) {
    LM_NOTICE("init_child [%d]  pid [%d]\n", rank, getpid());

    pid = my_pid();

    curl_global_init(CURL_GLOBAL_ALL);
    // initialize curl handle
    curl = curl_easy_init();
    if (!curl) {
        LM_ERR("Child %d: Curl initialization failed.\n", rank);
        return -1;
    }
    //create some connections before actual requests come.
    curl_head(URL);
    return 0;
}

我创建了一个C文件,其中创建了函数来处理GET / POST / PUT等请求:

int curl_head(const char* url) {
    if (!url) {
        LM_ERR("URL not provided. Returning with error.\n");
        return -1;
    }
    CURLcode res;
    int http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "charsets: utf-8");

    /* set URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
    curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);

    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        LM_ERR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }
    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    LM_DBG("HTTP return CODE %d\n", http_code);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return http_code;
}

int curl_post(const char* url, char *postdata) {
    if (!url) {
        LM_ERR("URL not provided. Returning with error.\n");
        return -1;
    }

    CURLcode res;

    int http_code = 0;
    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charsets: utf-8");

    /* set URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1");

    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        LM_ERR("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
    curl_slist_free_all(headers);
    curl_easy_reset(curl);
    return http_code;
}

当程序中的某个地方我想调用WS时,我将所需的函数称为curl_post(url)

我是否正确地执行此操作或在此实现中是否存在任何缺陷?

0 个答案:

没有答案