简介
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)