libcurl 发送 post 请求,请求体为 json 格式

本文介绍了如何使用 libcurl 库发送带有 JSON 格式请求体的 POST 请求,包括 libcurl 的安装、使用方法以及编译示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

参考文章

libcurl 使用示例

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值