libcurl 发送 post 请求,请求体为 json 格式
安装 libcurl
sudo apt install libcurl
使用 libcurl
使用 jsoncpp
创建 json 格式字符串,如果没有安装 jsoncpp
可以使用 apt install jsoncpp
安装
#define CURL_STATICLIB
#include <curl/curl.h>
#include <jsoncpp/json/json.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <chrono>
size_t ReceiveData(void *contents, size_t size, size_t nmemb, void *stream)
{
std::string *str = (std::string *)stream;
(*str).append((char *)contents, size * nmemb);
return size * nmemb;
}
CURLcode HttpPost(const std::string &url, const std::string &data, std::string &response, int timeout = 300)
{
CURLcode res;
CURL *curl = curl_easy_init();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
if (curl == NULL)
{
return CURLE_FAILED_INIT;
}
// 设置请求地址
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// 设置请求头信息
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 不显示接收头信息
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
// 设置请求超时时间
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, timeout);
// 设置请求体
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
// 设置接收函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ReceiveData);
// 设置接收内容
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return res;
}
int main()
{
auto start = std::chrono::system_clock::now();
Json::Value root;
root["text"] = "喂喂喂,你好。";
std::string url = "http://192.168.1.79:9001/api/asr/csc/";
std::string response;
CURLcode res = HttpPost(url, root.toStyledString(), response);
std::chrono::duration<double> duration = std::chrono::system_clock::now() - start;
std::cout << "Post used time: " << duration.count() << "\n";
if (res != CURLE_OK)
{
fprintf(stderr, "Failed: %s\n", curl_easy_strerror(res));
}
duration = std::chrono::system_clock::now() - start;
std::cout << "total used time: " << duration.count() << "\n";
Json::Reader reader;
Json::Value output;
reader.parse(response, output);
std::cout << "checked_sentence: " << output["checked_sentence"].toStyledString() << "\n";
return 0;
}
编译
g++ -std=c++11 main.cc -lcurl -ljsoncpp -o main