#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