C++ Poco库的编译和使用
flyfish
环境
Ubuntu18.04 Qt 5.14.2
源码下载地址
https://github.com/pocoproject/poco
编译依次执行
./configure --no-tests --no-samples --config=Linux --omit=Data --shared --static
make
sudo make install
–omit表示排除项目,Data中的SQlite,MySQL,ODBC等排除掉,这里不编译 如果要指定安装目录需要加参数 --prefix ,这里是默认目录安装到
/usr/local/lib
/usr/local/include
以http为例说明如何使用
CMakeLists.txt文件配置
cmake_minimum_required(VERSION 3.5)
project(example LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# set the POCO paths and libs
set(POCO_PREFIX "/usr/local") # the directory containing "include" and "lib"
set(POCO_INCLUDE_DIR"${POCO_PREFIX}/include")
set(POCO_LIB_DIR "${POCO_PREFIX}/lib")
set(POCO_LIBS
"${POCO_LIB_DIR}/libPocoNet.so"
"${POCO_LIB_DIR}/libPocoUtil.so"
"${POCO_LIB_DIR}/libPocoFoundation.so"
"${POCO_LIB_DIR}/libPocoNetSSL.so")
add_executable(example
main.cpp
)
target_link_libraries(example "${POCO_LIBS}")
代码实现
#include <iostream>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/URI.h>
#include <Poco/Net/HTTPCredentials.h>
#include <Poco/StreamCopier.h>
#include <Poco/Net/HTMLForm.h>
#include <Poco/BinaryReader.h>
#include <Poco/StreamConverter.h>
#include <Poco/Net/HTTPBasicCredentials.h>
#include <string>
#include <streambuf>
#include <Poco/Net/FilePartSource.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/NetException.h>
#include <Poco/Net/HTTPSClientSession.h>
int main(int argc, char *argv[])
{
try
{
Poco::URI url("https://docs.pocoproject.org/current/");
Poco::Net::HTTPSClientSession session(url.getHost(),url.getPort());
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET,url.getPathAndQuery());
session.sendRequest(req);
Poco::Net::HTTPResponse res;
std::istream & rs = session.receiveResponse(res);
Poco::Net::HTTPResponse::HTTPStatus status = res.getStatus();
std::string result;
Poco::StreamCopier::copyToString(rs, result);
if (Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK == status)
{
std::cout << "status HTTP_OK:"<<status<<std::endl;
}
else
{
Poco::StreamCopier::copyToString(rs, result);
std::cout << "status error:"<<status<<std::endl;
}
std::cout << "getReason:"<<res.getReason() <<result<<std::endl;
std::cout << "result:"<<result<<std::endl;
}
catch(Poco::Exception & ex)
{
std::cerr <<"exception error:"<< ex.displayText() << std::endl;
}
}
当成功的时候,result存储的返回网页的内容,其中getReason的内容已经包括result的内容。 以上是PC版本Poco库的编译和使用
POCO交叉编译配置
CMAKE_CXX_FLAGS:STRING= -pthread -ldl -lrt
文档中说SyslogChannel只应用于unix系统,防止在嵌入式系统中出现问题, 这里在config.h定义
#define POCO_NO_SYSLOGCHANNEL
|