本文整理汇总了C++中poco::net::HTTPResponse类的典型用法代码示例。如果您正苦于以下问题:C++ HTTPResponse类的具体用法?C++ HTTPResponse怎么用?C++ HTTPResponse使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTTPResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: uri
Poco::AutoPtr<Poco::XML::Document> Twitter::invoke(const std::string& httpMethod, const std::string& twitterMethod, Poco::Net::HTMLForm& form)
{
// Create the request URI.
// We use the XML version of the Twitter API.
Poco::URI uri(_uri + twitterMethod + ".xml");
std::string path(uri.getPath());
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
Poco::Net::HTTPRequest req(httpMethod, path, Poco::Net::HTTPMessage::HTTP_1_1);
// Add username and password (HTTP basic authentication) to the request.
Poco::Net::HTTPBasicCredentials cred(_username, _password);
cred.authenticate(req);
// Send the request.
form.prepareSubmit(req);
std::ostream& ostr = session.sendRequest(req);
form.write(ostr);
// Receive the response.
Poco::Net::HTTPResponse res;
std::istream& rs = session.receiveResponse(res);
// Create a DOM document from the response.
Poco::XML::DOMParser parser;
parser.setFeature(Poco::XML::DOMParser::FEATURE_FILTER_WHITESPACE, true);
parser.setFeature(Poco::XML::XMLReader::FEATURE_NAMESPACES, false);
Poco::XML::InputSource source(rs);
Poco::AutoPtr<Poco::XML::Document> pDoc = parser.parse(&source);
// If everything went fine, return the XML document.
// Otherwise look for an error message in the XML document.
if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
{
return pDoc;
}
else
{
std::string error(res.getReason());
Poco::AutoPtr<Poco::XML::NodeList> pList = pDoc->getElementsByTagName("error");
if (pList->length() > 0)
{
error += ": ";
error += pList->item(0)->innerText();
}
throw Poco::ApplicationException("Twitter Error", error);
}
}
示例2: testLoleafletPost
void HTTPServerTest::testLoleafletPost()
{
std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/loleaflet/dist/loleaflet.html");
Poco::Net::HTMLForm form;
form.set("access_token", "2222222222");
form.prepareSubmit(request);
std::ostream& ostr = session->sendRequest(request);
form.write(ostr);
Poco::Net::HTTPResponse response;
std::istream& rs = session->receiveResponse(response);
CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());
std::string html;
Poco::StreamCopier::copyToString(rs, html);
CPPUNIT_ASSERT(html.find(form["access_token"]) != std::string::npos);
CPPUNIT_ASSERT(html.find(_uri.getHost()) != std::string::npos);
}
示例3: testBadRequest
void HTTPWSTest::testBadRequest()
{
try
{
// Load a document and get its status.
const std::string documentURL = "file:///fake.doc";
Poco::Net::HTTPResponse response;
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, documentURL);
#if ENABLE_SSL
Poco::Net::HTTPSClientSession session(_uri.getHost(), _uri.getPort());
#else
Poco::Net::HTTPClientSession session(_uri.getHost(), _uri.getPort());
#endif
// This should result in Bad Request, but results in:
// WebSocket Exception: Missing Sec-WebSocket-Key in handshake request
// So Service Unavailable is returned.
request.set("Connection", "Upgrade");
request.set("Upgrade", "websocket");
request.set("Sec-WebSocket-Version", "13");
request.set("Sec-WebSocket-Key", "");
request.setChunkedTransferEncoding(false);
session.setKeepAlive(true);
session.sendRequest(request);
session.receiveResponse(response);
CPPUNIT_ASSERT(response.getStatus() == Poco::Net::HTTPResponse::HTTPResponse::HTTP_SERVICE_UNAVAILABLE);
}
catch (const Poco::Exception& exc)
{
CPPUNIT_FAIL(exc.displayText());
}
}
示例4: publish
/**
* Stream the contents of a file to a given URL.
* @param fileContents :: The contents of the file to publish.
* @param uploadURL :: The REST URL to stream the data from the file to.
*/
void CatalogPublish::publish(std::istream &fileContents,
const std::string &uploadURL) {
try {
Poco::URI uri(uploadURL);
std::string path(uri.getPathAndQuery());
Poco::SharedPtr<Poco::Net::InvalidCertificateHandler> certificateHandler =
new Poco::Net::AcceptCertificateHandler(true);
// Currently do not use any means of authentication. This should be updated
// IDS has signed certificate.
const Poco::Net::Context::Ptr context =
new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "",
Poco::Net::Context::VERIFY_NONE);
// Create a singleton for holding the default context. E.g. any future
// requests to publish are made to this certificate and context.
Poco::Net::SSLManager::instance().initializeClient(NULL, certificateHandler,
context);
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(),
context);
// Send the HTTP request, and obtain the output stream to write to. E.g. the
// data to publish to the server.
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_PUT, path,
Poco::Net::HTTPMessage::HTTP_1_1);
// Sets the encoding type of the request. This enables us to stream data to
// the server.
request.setChunkedTransferEncoding(true);
std::ostream &os = session.sendRequest(request);
// Copy data from the input stream to the server (request) output stream.
Poco::StreamCopier::copyStream(fileContents, os);
// Close the request by requesting a response.
Poco::Net::HTTPResponse response;
// Store the response for use IF an error occurs (e.g. 404).
std::istream &responseStream = session.receiveResponse(response);
// Obtain the status returned by the server to verify if it was a success.
Poco::Net::HTTPResponse::HTTPStatus HTTPStatus = response.getStatus();
// The error message returned by the IDS (if one exists).
std::string IDSError =
CatalogAlgorithmHelper().getIDSError(HTTPStatus, responseStream);
// Cancel the algorithm and display the message if it exists.
if (!IDSError.empty()) {
// As an error occurred we must cancel the algorithm.
// We cannot throw an exception here otherwise it is caught below as
// Poco::Exception catches runtimes,
// and then the I/O error is thrown as it is generated above first.
this->cancel();
// Output an appropriate error message from the JSON object returned by
// the IDS.
g_log.error(IDSError);
}
} catch (Poco::Net::SSLException &error) {
throw std::runtime_error(error.displayText());
}
// This is bad, but is needed to catch a POCO I/O error.
// For more info see comments (of I/O error) in CatalogDownloadDataFiles.cpp
catch (Poco::Exception &) {
}
}
示例5: masksReady
void ServerAccess::masksReady(std::string uuid, std::string message)
{
Poco::URI uri(server_address + "/api/calibrations/" + uuid + "/masksReady");
//std::string url = server_address + "/api/screens";
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
//prepare path
std::string path(uri.getPath());
//prepare and send request
std::string reqBody(message);
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
req.setContentType("application/json");
req.setContentLength(reqBody.length());
req.setKeepAlive(true);
std::ostream& oustr = session.sendRequest(req);
//oustr << results;
oustr << reqBody;
req.write(std::cout);
//get response
Poco::Net::HTTPResponse res;
std::cout << res.getStatus() << res.getReason() << std::endl;
std::istream &is = session.receiveResponse(res);
Poco::StreamCopier::copyStream(is, std::cout);
}
示例6: forward
void LocalPortForwarder::forward(Poco::Net::StreamSocket& socket)
{
if (_logger.debug())
{
_logger.debug(Poco::format("Local connection accepted, creating forwarding connection to %s, remote port %hu", _remoteURI.toString(), _remotePort));
}
try
{
std::string path(_remoteURI.getPathEtc());
if (path.empty()) path = "/";
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPRequest::HTTP_1_1);
request.set(SEC_WEBSOCKET_PROTOCOL, WEBTUNNEL_PROTOCOL);
request.set(X_WEBTUNNEL_REMOTEPORT, Poco::NumberFormatter::format(_remotePort));
Poco::Net::HTTPResponse response;
Poco::SharedPtr<Poco::Net::WebSocket> pWebSocket = _pWebSocketFactory->createWebSocket(_remoteURI, request, response);
if (response.get(SEC_WEBSOCKET_PROTOCOL, "") != WEBTUNNEL_PROTOCOL)
{
_logger.error("The remote host does not support the WebTunnel protocol.");
pWebSocket->shutdown(Poco::Net::WebSocket::WS_PROTOCOL_ERROR);
pWebSocket->close();
socket.close();
return;
}
_pDispatcher->addSocket(socket, new StreamSocketToWebSocketForwarder(_pDispatcher, pWebSocket), _localTimeout);
_pDispatcher->addSocket(*pWebSocket, new WebSocketToStreamSocketForwarder(_pDispatcher, socket), _remoteTimeout);
}
catch (Poco::Exception& exc)
{
_logger.error(Poco::format("Failed to open forwarding connection: %s", exc.displayText()));
socket.close();
}
}
示例7: verify
bool verify(const std::string& token) override
{
const std::string url = _authVerifyUrl + token;
Log::debug("Verifying authorization token from: " + url);
Poco::URI uri(url);
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, url, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse response;
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
Log::info() << "Status: " << response.getStatus() << " " << response.getReason() << Log::end;
std::string reply(std::istreambuf_iterator<char>(rs), {});
Log::info("Response: " + reply);
//TODO: Parse the response.
/*
// This is used for the demo site.
const auto lastLogTime = std::strtoul(reply.c_str(), nullptr, 0);
if (lastLogTime < 1)
{
//TODO: Redirect to login page.
return;
}
*/
return true;
}
示例8: run
void STEAMGET::run()
{
response = 0;
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
session->sendRequest(request);
#ifdef TESTING
extension_ptr->console->info("{0}", path);
#endif
#ifdef DEBUG_LOGGING
extension_ptr->logger->info("{0}", path);
#endif
Poco::Net::HTTPResponse res;
if (res.getStatus() == Poco::Net::HTTPResponse::HTTP_OK)
{
try
{
std::istream &is = session->receiveResponse(res);
boost::property_tree::read_json(is, *pt);
response = 1;
}
catch (boost::property_tree::json_parser::json_parser_error &e)
{
#ifdef TESTING
extension_ptr->console->error("extDB2: Steam: Parsing Error Message: {0}, URI: {1}", e.message(), path);
#endif
extension_ptr->logger->error("extDB2: Steam: Parsing Error Message: {0}, URI: {1}", e.message(), path);
response = -1;
}
}
}
示例9: sendRequest
bool myClientInteractor::sendRequest(Poco::Net::HTTPClientSession& session, Poco::Net::HTTPRequest& request, Poco::Net::HTTPResponse& response){
//tracker->stringify(std::cout, 0);
try{
str.clear();
tracker->stringify(str, 0);
str >> json;
//std::cout << "Sending: " << json << std::endl;
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
std::ostream& os = session.sendRequest(request);
//std::cout << "HERE NO PROBLEMS!!" << std::endl;
os << json;
return true;
}
else
{
//std::cout << "NULL!!!!" << std::endl;
Poco::NullOutputStream null;
//StreamCopier::copyStream(rs, null);
return false;
}
}catch(Exception& exc)
{
std::cerr << exc.displayText() << std::endl;
return 1;
}
}
示例10: testDiscovery
void HTTPServerTest::testDiscovery()
{
std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, "/hosting/discovery");
session->sendRequest(request);
Poco::Net::HTTPResponse response;
session->receiveResponse(response);
CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());
CPPUNIT_ASSERT_EQUAL(std::string("text/xml"), response.getContentType());
}
示例11: sendCommandJSON
bool sendCommandJSON(const std::string & method, Poco::Dynamic::Var & output, const std::vector<Poco::Dynamic::Var> & params = std::vector<Poco::Dynamic::Var>())
{
// Create request
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/jsonrpc");
// Authorization
request.set("Authorization", "Basic bnpiZ2V0OnRlZ2J6bg==");
// Create body
Poco::Dynamic::Var body = Poco::Dynamic::Struct<std::string>();
body["method"] = method;
body["id"] = "sendCommandJSON";
std::vector<Poco::Dynamic::Var> params_;
params_.push_back("callback");
for (std::vector<Poco::Dynamic::Var>::const_iterator it = params.begin(); it != params.end(); ++it)
{
params_.push_back(*it);
}
body["params"] = params_;
std::string body_ = MyVideoCollection::JSON::stringify(body);
request.setContentLength(body_.length());
// Send request
Poco::Net::HTTPClientSession session("127.0.0.1", port_);
session.sendRequest(request) << body_ << std::flush;
// Receive response
Poco::Net::HTTPResponse response;
std::istream & responseStream = session.receiveResponse(response);
std::size_t bytes = response.getContentLength();
std::stringstream response_;
while (bytes > 0 && responseStream.good())
{
char buf[4096];
responseStream.read(buf, std::min(bytes, (std::size_t)4096));
std::size_t gcount = responseStream.gcount();
bytes -= gcount;
response_ << std::string(buf, gcount);
}
// Parse JSON
output = MyVideoCollection::JSON::parse(response_);
// Result?
if (!output.isStruct())
{
output.empty();
return false;
}
output = output["result"];
return true;
}
示例12: parse
void ForecastSensor::parse() {
r.clear();
try {
std::cout << "get url: " << url << std::endl;
//http://www.yr.no/place/Czech_Republic/Central_Bohemia/%C4%8Cerven%C3%A9_Pe%C4%8Dky/forecast_hour_by_hour.xml
Poco::URI uri(url);
std::string path(uri.getPathAndQuery());
Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_0);
Poco::Net::HTTPResponse response;
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_OK) {
throw Poco::Exception("Cannot get remote data");
}
//Poco::StreamCopier::copyStream(rs, std::cout);
Poco::XML::InputSource src(rs);
ForecastParser handler;
handler.Forecast += Poco::delegate(this, &ForecastSensor::onData);
Poco::XML::SAXParser parser;
parser.setContentHandler(&handler);
try {
std::cout << "parse" << std::endl;
parser.parse(&src);
} catch (Poco::Exception& e) {
std::cerr << e.displayText() << std::endl;
}
handler.Forecast -= Poco::delegate(this, &ForecastSensor::onData);
} catch (Poco::Exception& exc) {
std::cerr << exc.displayText() << std::endl;
}
}
示例13: preprocessAdminFile
void FileServerRequestHandler::preprocessAdminFile(const HTTPRequest& request,const std::shared_ptr<StreamSocket>& socket)
{
Poco::Net::HTTPResponse response;
if (!LOOLWSD::AdminEnabled)
throw Poco::FileAccessDeniedException("Admin console disabled");
if (!FileServerRequestHandler::isAdminLoggedIn(request, response))
throw Poco::Net::NotAuthenticatedException("Invalid admin login");
static const std::string scriptJS("<script src=\"%s/loleaflet/" LOOLWSD_VERSION_HASH "/%s.js\"></script>");
static const std::string footerPage("<div class=\"footer navbar-fixed-bottom text-info text-center\"><strong>Key:</strong> %s <strong>Expiry Date:</strong> %s</div>");
const std::string relPath = getRequestPathname(request);
LOG_DBG("Preprocessing file: " << relPath);
std::string adminFile = *getUncompressedFile(relPath);
std::string brandJS(Poco::format(scriptJS, LOOLWSD::ServiceRoot, std::string(BRANDING)));
std::string brandFooter;
#if ENABLE_SUPPORT_KEY
const auto& config = Application::instance().config();
const std::string keyString = config.getString("support_key", "");
SupportKey key(keyString);
if (!key.verify() || key.validDaysRemaining() <= 0)
{
brandJS = Poco::format(scriptJS, std::string(BRANDING_UNSUPPORTED));
brandFooter = Poco::format(footerPage, key.data(), Poco::DateTimeFormatter::format(key.expiry(), Poco::DateTimeFormat::RFC822_FORMAT));
}
#endif
Poco::replaceInPlace(adminFile, std::string("<!--%BRANDING_JS%-->"), brandJS);
Poco::replaceInPlace(adminFile, std::string("<!--%FOOTER%-->"), brandFooter);
Poco::replaceInPlace(adminFile, std::string("%VERSION%"), std::string(LOOLWSD_VERSION_HASH));
Poco::replaceInPlace(adminFile, std::string("%SERVICE_ROOT%"), LOOLWSD::ServiceRoot);
// Ask UAs to block if they detect any XSS attempt
response.add("X-XSS-Protection", "1; mode=block");
// No referrer-policy
response.add("Referrer-Policy", "no-referrer");
response.add("X-Content-Type-Options", "nosniff");
response.set("User-Agent", HTTP_AGENT_STRING);
response.set("Date", Poco::DateTimeFormatter::format(Poco::Timestamp(), Poco::DateTimeFormat::HTTP_FORMAT));
response.setContentType("text/html");
response.setChunkedTransferEncoding(false);
std::ostringstream oss;
response.write(oss);
oss << adminFile;
socket->send(oss.str());
}
示例14: testScriptsAndLinksGet
void HTTPServerTest::testScriptsAndLinksGet()
{
std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, "/loleaflet/dist/loleaflet.html");
session->sendRequest(request);
Poco::Net::HTTPResponse response;
std::istream& rs = session->receiveResponse(response);
CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());
std::string html;
Poco::StreamCopier::copyToString(rs, html);
Poco::RegularExpression script("<script.*?src=\"(.*?)\"");
assertHTTPFilesExist(_uri, script, html, "application/javascript");
Poco::RegularExpression link("<link.*?href=\"(.*?)\"");
assertHTTPFilesExist(_uri, link, html);
}
示例15: testLoleafletGet
void HTTPServerTest::testLoleafletGet()
{
std::unique_ptr<Poco::Net::HTTPClientSession> session(helpers::createSession(_uri));
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, "/loleaflet/dist/loleaflet.html?access_token=111111111");
Poco::Net::HTMLForm param(request);
session->sendRequest(request);
Poco::Net::HTTPResponse response;
std::istream& rs = session->receiveResponse(response);
CPPUNIT_ASSERT_EQUAL(Poco::Net::HTTPResponse::HTTP_OK, response.getStatus());
CPPUNIT_ASSERT_EQUAL(std::string("text/html"), response.getContentType());
std::string html;
Poco::StreamCopier::copyToString(rs, html);
CPPUNIT_ASSERT(html.find(param["access_token"]) != std::string::npos);
CPPUNIT_ASSERT(html.find(_uri.getHost()) != std::string::npos);
CPPUNIT_ASSERT(html.find(std::string(LOOLWSD_VERSION_HASH)) != std::string::npos);
}