使用C++的libcurl库实现HTTP的POST请求

15 篇文章 0 订阅

简介

libcurl库是由C语言编写的轻量级网络库。可以实现客户端的一些基本功能。本文使用libcurl库实现了HTTP的POST请求。

代码

C++代码

使用POST方式完成对以下两个API的访问
localhost:8050/api/dataLink
localhost:8050/api/startExe
实现函数见postRequest,以下是完整代码

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

CURLcode postRequest(CURL *curl, std::string apiUrl, std::string postContent)
{
    CURLcode res;
    curl = curl_easy_init();
    if (curl)
    {
        // 设置API的URL
        curl_easy_setopt(curl, CURLOPT_URL, apiUrl.c_str());
        // 设置请求头(使用json数据格式)
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        // 设置请求体内容
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postContent.c_str());
        // 发出请求
        res = curl_easy_perform(curl);
        std::cout << std::endl;
        // 检查是否出错
        if (res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));
        // 释放内存
        curl_easy_cleanup(curl);
    }
    return res;
}

int main(void)
{
    std::string baseUrl = "localhost:8050";
    CURL *curl;
    //反复发送请求100次
    for (int i = 0; i < 100; i++)
    {
        //第三个请求实例
        postRequest(curl, baseUrl + "/api/dataLink", "{ \"attribute\": \"source\" }");
        postRequest(curl, baseUrl + "/api/startExe", "");
        postRequest(curl, baseUrl + "/api/dataLink", "{ \"attribute\": \"sourceDelay\" }");
        std::cout << std::endl;
    }
    return 0;
}

CMakeLists.txt

编译后需要链接libcurl库

cmake_minimum_required(VERSION 3.0)
project(curlTest)
add_executable(curlTest main.cpp)
target_link_libraries(curlTest curl)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jedi-knight

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值