您的位置:首页 > Web前端 > JavaScript

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

2018-03-03 20:12 477 查看

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开始操作条件结束yesno
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: