头文件webapi.h
#pragma once #include <Poco/Net/HTTPClientSession.h> #include <Poco/Net/HTTPRequest.h> #include <Poco/Net/HTTPResponse.h> #include <Poco/StreamCopier.h> #include <Poco/Net/NetException.h> #include <Poco/Net/HTMLForm.h> #include <Poco/URI.h> #include <Poco/NumberParser.h> #include <Poco/String.h> #include <atomic> #include <string> using namespace std; class CWebApi { public: CWebApi(string baseUrl = ""); ~CWebApi(); void setBaseUrl(const string& baseUrl); string getBaseUrl(); bool httpGet(string api, string& resp, int32_t& status, string& errmsg); private: string baseUrl_; };
源文件webapi.cpp
#include "webapi.h" #include <iostream> #include "log.h" CWebApi::CWebApi(string baseUrl) :baseUrl_(baseUrl) { } CWebApi::~CWebApi() { } void CWebApi::setBaseUrl(const string& baseUrl) { baseUrl_ = baseUrl; } string CWebApi::getBaseUrl() { return baseUrl_; } bool CWebApi::httpGet(string api, string& resp, int32_t& status, string& errmsg) { LOG_INFO("BEGIN {}", api); bool ret = false; string strUrl; strUrl = baseUrl_ + api; try { Poco::URI httpUrl(strUrl); Poco::Net::HTTPClientSession session(httpUrl.getHost(), httpUrl.getPort()); session.setTimeout(Poco::Timespan(8, 0), Poco::Timespan(8, 0), Poco::Timespan(8, 0)); Poco::Net::HTTPRequest httpReq(Poco::Net::HTTPRequest::HTTP_GET, httpUrl.getPathAndQuery()); httpReq.add("Connection", "close"); session.sendRequest(httpReq); Poco::Net::HTTPResponse httpResp; istream& is = session.receiveResponse(httpResp); Poco::StreamCopier::copyToString(is, resp); status = httpResp.getStatus(); if (status == Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED) { LOG_DEBUG("WebAPI {}, configuration not modified!", strUrl); } if (status == Poco::Net::HTTPResponse::HTTP_OK || status == Poco::Net::HTTPResponse::HTTP_NOT_MODIFIED) { ret = true; } else { } session.reset(); } catch (Poco::Net::NetException & ex) { errmsg = ex.displayText(); } catch (std::exception& exc) { errmsg = exc.what(); } catch (...) { } if (!ret) { LOG_ERROR("WebAPI {} error, status = {}, errmsg = {}", strUrl, status, errmsg); } LOG_INFO("END {}", api); return ret; }