C/C++中用libcurl进行http请求,向ES中插入数据

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

int Insert(long arg1, long arg2, long arg3, long arg4, const char* arg5)
{
    CURL *curl;
    CURLcode res;
    //const char* str = "{\"time\":\"1542852001\",\"total\":\"100\",\"in\":\"20\",\"out\":\"80\",\"interface\":\"eth0\"}";
    char str[100];
    char url[100] = "http://192.168.1.200:9200/index/type/";

    sprintf(str, "{\"time\":%ld,\"total\":%ld,\"in\":%ld,\"out\":%ld,\"interface\":\"%s\"}", arg1, arg2, arg3, arg4, arg5);
    
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl!=NULL)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str);
        res = curl_easy_perform(curl);
        if(res != CURLE_OK)
            //fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            ErrPrintf("bandwidth error");
        curl_easy_cleanup(curl);
    }
    
    curl_global_cleanup();
    
    return 0;
}

注:
1) curl_global_init(CURL_GLOBAL_ALL);
在curl_easy_init函数调用时还没调用,它讲由libcurl库自动调用,所以多线程下最好主动调用该函数以防止在线程中curl_easy_init时多次调用。

2) curl_global_cleanup()
虽然libcurl是线程安全的,但curl_global_cleanup是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,应该将该函数的调用放在主线程中。

参考:
C++ 用libcurl库进行http通讯网络编程

curl库中curl_easy_setopt函数详解

官方例子

c/c++调用libcurl库发送http请求的两种基本用法

 

posted @ 2018-12-14 11:16  Hsinwang  阅读(930)  评论(0编辑  收藏  举报