libcurl實例使用:用post方式發送數據

今天得空來整理以前的筆記,看到了libcurl。稍微整理記錄再加上順帶複習一下。

一、準備

  1. 下載
    官網鏈接:https://curl.haxx.se/
  2. 編譯三步走
cd curl
./buildconf
./configure
make
sudo make install

二、程序實例-發送一個post請求

#include <curl/curl.h>

// 注意參數 size * nmemb 是數據的總長度
size_t wirte_callback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
    char* buf = (char *)malloc(size * nmemb + 1);
    memcpy(buf, ptr, size*nmemb);
    buf[size*nmemb] = 0;
    printf("recv data = %s\n", buf);
    printf("*********************\n");
    free(buf);
    return size * nmemb;
}

int main()
{
    CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
    if (code != CURLE_OK)
    {
        printf("global init err\n");
        return -1;
    }
	// 初始化
    CURL* curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.49.136:8081");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wirte_callback); // 設置回調函數
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);

    // 設置post提交方式
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    // 設置post的數據
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "this is post data");
    // 設置post的長度,如果是文本可以不用設置
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sizeof("this is post data"));

	// 發送
    code = curl_easy_perform(curl);
    if (code != CURLE_OK)
    {
        printf("perform err\n");
        return -2;
    }

    curl_easy_cleanup(curl);

    return 0;
}

三、總結

libcurl使用的還是比較簡單的,主要的函數就是curl_easy_setopt(),這個函數可以設置很多個數據,屬性,方式等等。。。同時這個參數在官網有詳細的說明,真的是太多了(鼠標拖了很久都沒到底的那種,官網屬性說明鏈接:https://curl.haxx.se/libcurl/c/curl_easy_setopt.html)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章