使用libcurl向服务器发送json文件并在服务器端处理

C++处理json

json内容

json有两种形式,一种是对象{“key”:”value”}.另一种是数组[{“one”:”1”},{“two”:”2”}]

jsoncpp库

jsoncpp是一个C++种处理json数据的库,下载地址为github地址.
然后生成jsoncpp头文件与cpp,把生成的dist文件夹加入工程就可以使用了,包括json/json.h,json/json-forwards.h,json.cpp.

python amalgamate.py

然后

#include<json/json.h>

Json::Value root;
Json::Value child;
root["one"]="1";
child["do"]="play";
root.append(child);

cout << jsonRoot.toStyledString() << endl; //输出到控制台

ps:在文件,内存中读取或解析json数据………….链接2

libcurl库

libcurl主要功能就是用不同的协议连接和沟通不同的服务器。 libcurl当前支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。下载地址
下载解压后,在该目录内执行如下:

 sudo ./configure

 sudo make  

 sudo make install

如果执行curl命令不行,export PATH=$PATH:/usr/local/curl/bin放入环境变量.
查看/usr/include中有没有curl文件夹,没有的话把curl中的include复制过去

cp -r curl-7.51.0/include/curl/ /usr/include/

查看头文件和库

curl-config --cflags //头文件地址
curl-config --libs //库函数地址

分别显示:

-I/usr/local/include
-L/usr/local/lib -lcurl //使用时需要加上-lcurl

POST例子

    #include <curl/curl.h>  
    #include <string>  
    #include <exception>  

    int main(int argc, char *argv[])   
    {  
        char szJsonData[1024];  
        memset(szJsonData, 0, sizeof(szJsonData));  
        std::string strJson = "{";  
        strJson += "\"user_name\" : \"test\",";  
        strJson += "\"password\" : \"test123\"";  
        strJson += "}";  
        strcpy(szJsonData, strJson.c_str());  
        try   
        {  
            CURL *pCurl = NULL;  
            CURLcode res;  
            // In windows, this will init the winsock stuff  
            curl_global_init(CURL_GLOBAL_ALL);  

            // get a curl handle  
            pCurl = curl_easy_init();  
            if (NULL != pCurl)   
            {  
                // 设置超时时间为1秒  
                curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);  

                // First set the URL that is about to receive our POST.   
                // This URL can just as well be a   
                // https:// URL if that is what should receive the data.  
                curl_easy_setopt(pCurl, CURLOPT_URL, "http://192.168.0.2/posttest.svc");  
                //curl_easy_setopt(pCurl, CURLOPT_URL, "http://192.168.0.2/posttest.cgi");  

                // 设置http发送的内容类型为JSON  
                curl_slist *plist = curl_slist_append(NULL,   
                    "Content-Type:application/json;charset=UTF-8");  
                curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);  

                // 设置要POST的JSON数据  
                curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);  

                // Perform the request, res will get the return code   
                res = curl_easy_perform(pCurl);  
                // Check for errors  
                if (res != CURLE_OK)   
                {  
                    printf("curl_easy_perform() failed:%s\n", curl_easy_strerror(res));  
                }  
                // always cleanup  
                curl_easy_cleanup(pCurl);  
            }  
            curl_global_cleanup();  
        }  
        catch (std::exception &ex)  
        {  
            printf("curl exception %s.\n", ex.what());  
        }  
        return 0;  
    }  

ps:代码来自http://blog.csdn.net/u010871058/article/details/62894030

python简单服务器处理json

# coding:utf-8 

import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler  
class RequestHandler(BaseHTTPRequestHandler):  
  def _writeheaders(self):  
    #print self.path  
    #print self.headers  
    self.send_response(200);  
    self.send_header('Content-type','text/html');  
    self.end_headers()  
  def do_Head(self):  
    self._writeheaders()  
  def do_GET(self):  
    self._writeheaders()


    self.wfile.write("""<!DOCTYPE HTML> 
<html lang="en-US"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
<p>this is get!</p> 
</body> 
</html>"""+str(self.headers))  


  def do_POST(self):  
    self._writeheaders()
    length = self.headers.getheader('content-length');
    nbytes = int(length)
    data = self.rfile.read(nbytes)
    text = json.loads(data)
    config_name = "camera"
    file = open(config_name + '.ini', 'w')
    file.write('[General]\n')
    for key in text:
        file.write(key+'='+text[key]+'\n')
    file.close()



    self.wfile.write("""<!DOCTYPE HTML> 
<html lang="en-US"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
<p>this is put!</p> 
</body> 
</html>"""+str(self.headers)+str(self.command)+str(self.headers.dict))  
addr = ('',8000)  
server = HTTPServer(addr,RequestHandler)  
server.serve_forever()

程序下载地址:http://download.csdn.net/download/san_junipero/10270114

markdown流程图绘制

st=>start: 开始   //空一个格
e=>end: 结束
op=>operation: 操作
cond=>condition: 条件

st->op->cond
cond(yes)->e
cond(no)->op
Created with Raphaël 2.1.2 开始 操作 条件 结束 yes no
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用libcurl库在Qt中发送HTTP请求,与Flask服务器进行通信。以下是一个简单的示例代码: ```c++ #include <QCoreApplication> #include <QDebug> #include <QUrl> #include <curl/curl.h> // 回调函数,用于处理curl请求的响应数据 size_t handle_response(char *buffer, size_t size, size_t nmemb, void *userdata) { QByteArray *response = static_cast<QByteArray*>(userdata); response->append(buffer, size * nmemb); return size * nmemb; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // 初始化curl curl_global_init(CURL_GLOBAL_ALL); CURL *curl = curl_easy_init(); // 设置请求的URL QUrl url("http://localhost:5000/api/test"); // 设置curl选项 curl_easy_setopt(curl, CURLOPT_URL, url.toString().toStdString().c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, handle_response); // 发送请求 QByteArray response; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); CURLcode result = curl_easy_perform(curl); if (result != CURLE_OK) { qDebug() << "Error: " << curl_easy_strerror(result); } else { qDebug() << "Response: " << response; } // 清理curl curl_easy_cleanup(curl); curl_global_cleanup(); return a.exec(); } ``` 在上面的示例中,我们使用了`curl_easy_setopt`函数设置了curl选项,包括请求的URL、是否跟随重定向、响应数据的处理函数等。我们使用了`curl_easy_perform`函数发送请求并获取响应数据,最后使用`curl_easy_cleanup`函数清理curl。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值