最近在研究使用C++代码访问用python语言的flask模块搭建的服务,记录了python服务端的代码,和C++客户端的代码。只需要把在C++开启一个控制台程序并且搭建好POCOJSON库环境就可以访问该python服务了。本文记录了一个小测试项目,方便初学者入门。
首先,让我们了解一下POCO的基础操作。
一、python 搭建服务端:
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
import json
app = Flask(__name__)
api = Api(app)
TODOS = {}
parser = reqparse.RequestParser()
parser.add_argument('x', required=True, action='append', help="x cannot be blank!")
parser.add_argument('y', required=True, action='append', help="y cannot be blank!")
parser.add_argument('z', required=True, action='append', help="z cannot be blank!")
class Todo(Resource):
def get(self):
return TODOS
def delete(self):
del TODOS
return '', 204
def post(self):
args = parser.parse_args()
x = {'x': args['x']}
y = {'y': args['y']}
z = {'z': args['z']}
TODOS.update(x)
TODOS.update(y)
TODOS.update(z)
return TODOS, 200
api.add_resource(Todo, '/todos')
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
二、C++ 客户端访问 python 搭建的服务端:
POCO_JSON 环境文件下载,免编译(https://download.csdn.net/download/qq_35591253/86870630)
.h 头文件中定义函数
#pragma once
#include "string"
std::string postWithJSON(const std::string& i_uriStr, const std::string& i_strInput);
.cpp 中执行控制台程序
#include <iostream>
#include "pocoJsonTest1.h"
#include "Poco\JSON\Object.h"
#include "Poco\JSON\JSON.h"
#include "Poco\Net\HTTPClientSession.h"
#include "Poco\Net\HTTPRequest.h"
#include "Poco\Net\HTTPMessage.h"
#include "Poco\URI.h"
#include "Poco\Net\HTTPResponse.h"
#include "Poco\StreamCopier.h"
using namespace std;
using namespace Poco;
using namespace JSON;
using namespace Net;
int main()
{
std::cout << "Hello World!\n\n";
Poco::JSON::Object testInforJsonObj;
testInforJsonObj.set("x", "1.2,1.3,1.4");//输入参数
testInforJsonObj.set("y", "1.2,1.3,1.4");
testInforJsonObj.set("z", "1.2,1.3,1.4");
/*Poco::JSON::Array xArray;//输入矩阵
Poco::JSON::Array yArray;
Poco::JSON::Array zArray;
for (int i = 0; i < 10; i++)
{
xArray.add(0.1 * i);
yArray.add(1.0 * i);
zArray.add(10.0 * i);
}
roadwayInforJsonObj.set("x", xArray);
roadwayInforJsonObj.set("y", yArray);
roadwayInforJsonObj.set("z", zArray);*/
std::ostringstream oStrStream;
try
{
testInforJsonObj.stringify(oStrStream, 2);
}
catch (const std::exception&)
{
/*if (oStrStream.str().empty())
return testInforJsonStr;
return 0;*/
}
const std::string str = oStrStream.str();//传入的参数
const std::string url = "http://127.0.0.1:5000/todos";//访问ip和端口
const std::string result = postWithJSON(url, str);
std::cout << result << std::endl;
return 0;
}
std::string postWithJSON(const std::string& i_uriStr, const std::string& i_strInput)
{
std::string responseResult;
try
{
URI uri(i_uriStr);
std::string path(uri.getPathAndQuery());
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;
//设置超时时间(单位 微秒)
//设置类型为application/json
request.setContentType("application/json");
request.setContentLength((int)i_strInput.length());
//发送数据
session.sendRequest(request) << i_strInput;
//接收返回结果
std::istream& rs = session.receiveResponse(response);
int result = (int)response.getStatus();
const std::string& s1 = response.getTransferEncoding();
const std::string& s2 = response.getReason();
response.getChunkedTransferEncoding();
if (result == Poco::Net::HTTPResponse::HTTP_OK)
{
//成功
Poco::StreamCopier copier;
copier.copyToString(rs, responseResult);
}
}
catch (...)
{
}
return responseResult;
}
三、附加:POCO 基础操作(GET)
Poco 是一个 C++ 网络库,用于创建网络应用程序。它包含一组可以用来构建网络客户端和服务器的工具,支持多种网络协议,如 HTTP、SMTP、FTP 等。
使用 Poco 访问服务,您需要创建一个 Poco 对象,并使用它来建立连接。然后,您就可以使用 Poco 发送请求和接收响应了。
下面是一个简单的例子,展示了如何使用 Poco 访问 HTTP 服务:
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <iostream>
#include <string>
int main(int argc, char** argv)
{
// 创建 Poco 对象
Poco::URI uri("http://www.example.com/");
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
// 发送请求
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
session.sendRequest(request);
// 接收响应
Poco::Net::HTTPResponse response;
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
// 处理响应内容
std::string content;
Poco::StreamCopier::copyToString(rs, content);
std::cout << content << std::endl;
return 0;
}
四、注意事项
① python端服务的防火墙要关闭;
② python端的真正IP要找到;
③ python端服务不能停;
④ C++端的url要输对,检查端口和接口;
⑤ python服务可以用postman测试。