c++ curl 传输json数组

#include <iostream>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <curl/curl.h>

using namespace std;

int upload(string url, string strData)
{
    CURL *curl = NULL;
    struct curl_slist *headers = NULL;//报文头
    curl_global_init(CURL_GLOBAL_ALL);

    curl = curl_easy_init();

    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");//text/html
    headers = curl_slist_append(headers, "charsets: utf-8");

    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");

    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strData.c_str());
    // 输出响应头等信息
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    // 屏蔽输出响应头等信息
    curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
    curl_easy_setopt(curl, CURLOPT_HEADER, 0L);

    int res = curl_easy_perform(curl);
    cout<<endl;

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return res;
}

int main()
{
    cout << "Hello World!" << endl;

    Json::Value root;
    root["a"] = "hello";
    root["b"] = "world";

    Json::FastWriter fw;
    cout<<"json Data: "<<fw.write(root)<<endl;

    string strData = root.toStyledString();
    string url = "http://192.168.1.2:8888/code?id=" + to_string(random());
    cout<<url<<endl;

    int res = upload(url, strData);
    cout<<res<<endl;

    return 0;
}

编译:
g++ main.cpp -ljsoncpp -lcurl

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值