当我在没有网络连接的情况下运行以下代码时,我在最后一行遇到错误的访问错误。
Poco::URI uri(sRemoteLoggingURL);
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPathAndQuery());
request.set("User-Agent", "Poco");
string reqBody = "{\"logMessage\":\""+ message + "\", \"application_name\":\""+ sAppName +"\"}";
request.setContentLength( reqBody.length() );
std::ostream& sessionStream = session.sendRequest(request);
这是预期的行为吗?在尝试发送请求之前,是否需要检查网络连接?如果是这样,我该怎么做?我已尝试session.connected()
,但即使我有网络连接,也会返回false。
答案 0 :(得分:0)
我想我明白了。显然,如果有异常,您需要确保在销毁之前(或在它超出范围之前)在会话上调用reset
。此代码有效:
Poco::URI uri(sRemoteLoggingURL);
HTTPClientSession session(uri.getHost(), uri.getPort());
try{
HTTPRequest request(HTTPRequest::HTTP_POST, uri.getPathAndQuery());
request.set("User-Agent", "Poco");
string reqBody = "{\"logMessage\":\""+ message + "\", \"application_name\":\""+ sAppName +"\"}";
request.setContentLength( reqBody.length() );
std::ostream& sessionStream = session.sendRequest(request);
if (sessionStream.good()) {
sessionStream << reqBody;
HTTPResponse res;
string text;
istream &is = session.receiveResponse(res);
StreamCopier::copyToString(is, text);
}
}catch(Poco::Exception& e){
// apparently, you MUST call reset before destroying the session, or you'll crash
session.reset();
sdfLog::logFormat("appContent::doIdle Poco::Exception: %s\n", e.what());
}catch(...){
session.reset();
sdfLog::logFormat("appContent::doIdle exception in remote logger %s\n");
}