示例#1
1
文件: Twitter.cpp 项目: as2120/ZPoco
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);
    }
}
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
0
文件: http.cpp 项目: ruslanec/waha
bool RESTHandler::build_message(Poco::Net::HTTPServerRequest &request, Poco::Net::HTMLForm &form, Poco::URI &url,
                                zmqpp::message &msg) {

    Json::Value root;
    bool ok = false;
    /// Find 'args' param in query or as POST body
    if (form.has("args")) {
        ok = reader.parse(form.get("args"), root);
    } else if (request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST) {
        ok = reader.parse(request.stream(), root);
    }
    if (!ok || !root.isArray()) {
        return false;
    }
    if (verbose) {
        std::clog << "0\t" << url.getPath().substr(1) << std::endl;
    }
    /// Get service name as path without leading slash
    msg << url.getPath().substr(1);
    for (size_t i = 0; i < root.size(); ++i) {
        auto val = root.get(i, "");
        if (!verbose)
            msg << (val.isString() ? root.get(i, "").asString() : val.toStyledString());
        else {
            std::string s = (val.isString() ? root.get(i, "").asString() : val.toStyledString());
            msg << s;
            std::clog << (i + 1) << '\t' << s << std::endl;
        }
    }
    return true;
}
示例#4
0
void HTMLFormWrapper::hasField(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (args.Length() < 1) return;
	Poco::Net::HTMLForm* pForm = Wrapper::unwrapNative<Poco::Net::HTMLForm>(args);
	std::string name = toString(args[0]);
	bool result = pForm->has(name);
	args.GetReturnValue().Set(result);
}
示例#5
0
void HTMLFormWrapper::getField(const v8::FunctionCallbackInfo<v8::Value>& args)
{
	if (args.Length() < 1) return;
	Poco::Net::HTMLForm* pForm = Wrapper::unwrapNative<Poco::Net::HTMLForm>(args);
	std::string name = toString(args[0]);
	std::string deflt;
	if (args.Length() > 1) deflt = toString(args[1]);
	std::string value = pForm->get(name, deflt);
	returnString(args, value);
}
示例#6
0
bool TrafficPage::handleForm(Poco::Net::HTMLForm& form, Poco::Net::HTTPServerRequest&, Poco::Net::HTTPServerResponse &)
{
    _local = form.has("local");
    _all = form.has("all");
    if (form.has("filter")) {
        _group = form.get("filter");
        if (_group == "IP") {
            _group = "traffic.ip";
        }
    }
    return false;
}
示例#7
0
文件: Twitter.cpp 项目: as2120/ZPoco
Poco::Int64 Twitter::update(const std::string& status)
{
    Poco::Net::HTMLForm form;
    form.set("status", status);
    Poco::AutoPtr<Poco::XML::Document> pResult = invoke(Poco::Net::HTTPRequest::HTTP_POST, "update", form);
    Poco::AutoPtr<Poco::XML::NodeList> pList = pResult->getElementsByTagName("id");
    if (pList->length() > 0)
    {
        return Poco::NumberParser::parse64(pList->item(0)->innerText());
    }
    else return 0;
}
/** Sets the body & content length for future requests, this will also
*   set the method to POST is the body is not empty
*   and GET if it is.
* @param form A HTMLform
**/
void InternetHelper::setBody(Poco::Net::HTMLForm &form) {

  setMethod("POST");
  if (m_request == nullptr) {
    Poco::URI uri("http://www.mantidproject.org");
    createRequest(uri);
  }
  form.prepareSubmit(*m_request);
  setContentType(m_request->getContentType());

  std::ostringstream ss;
  form.write(ss);
  m_body = ss.str();
  setContentLength(m_body.size());
}
void Service::processQuery(const Poco::Net::HTMLForm & params, ReadBuffer & body, WriteBuffer & out)
{
	if (is_cancelled)
		throw Exception{"RemoteQueryExecutor service terminated", ErrorCodes::ABORTED};

	std::string query = params.get("query");

	bool flag = true;

	try
	{
		(void) executeQuery(query, context, true);
	}
	catch (...)
	{
		tryLogCurrentException(__PRETTY_FUNCTION__);
		flag = false;
	}

	writeBinary(flag, out);
	out.next();
}
void OAuthPrivate::resourceFile(const std::string method, const std::string url, const std::string & filename, const std::string status){
	std::string authStr = buildAuthHeader(method, url, Params());
	authStr = "OAuth " + authStr;

	URI uri(url);
	std::string path(uri.getPathAndQuery());
	if (path.empty()) path = "/";

	const Poco::Net::Context::Ptr context( new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", "cacert.pem"));
	HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
	HTTPRequest request(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
	HTTPResponse response;

	Poco::Net::HTMLForm form;
	form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);

	form.set("status", status);
	
	form.addPart("media[]", new Poco::Net::FilePartSource(filename, filename, "application/octet-stream"));
	form.prepareSubmit(request);

	request.set("Authorization", authStr);
	
	std::ostream & ostr = session.sendRequest(request);
	form.write(ostr);

	std::istream& rs = session.receiveResponse(response);
	std::cout << response.getStatus() << " " << response.getReason() << std::endl;

	if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
	{
		StreamCopier::copyStream(rs, std::cout);
	}
	else
	{
		Poco::NullOutputStream null;
		StreamCopier::copyStream(rs, null);
	}
}
示例#11
0
void HTTPPostTest::testConvertTo()
{
    const auto srcPath = Util::getTempFilePath(TDOC, "hello.odt");

    Poco::URI uri("https://127.0.0.1:" + std::to_string(ClientPortNumber));
    Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort());

    Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/convert-to");
    Poco::Net::HTMLForm form;
    form.setEncoding(Poco::Net::HTMLForm::ENCODING_MULTIPART);
    form.set("format", "txt");
    form.addPart("data", new Poco::Net::FilePartSource(srcPath));
    form.prepareSubmit(request);
    // If this results in a Poco::Net::ConnectionRefusedException, loolwsd is not running.
    form.write(session.sendRequest(request));

    Poco::Net::HTTPResponse response;
    std::stringstream actualStream;
    // receiveResponse() resulted in a Poco::Net::NoMessageException.
    std::istream& responseStream = session.receiveResponse(response);
    Poco::StreamCopier::copyStream(responseStream, actualStream);

    std::ifstream fileStream(TDOC "/hello.txt");
    std::stringstream expectedStream;
    expectedStream << fileStream.rdbuf();

    // Remove the temp files.
    Util::removeFile(srcPath);

    // In some cases the result is prefixed with (the UTF-8 encoding of) the Unicode BOM
    // (U+FEFF). Skip that.
    std::string actualString = actualStream.str();
    if (actualString.size() > 3 && actualString[0] == '\xEF' && actualString[1] == '\xBB' && actualString[2] == '\xBF')
        actualString = actualString.substr(3);
    CPPUNIT_ASSERT_EQUAL(expectedStream.str(), actualString);
}
示例#12
0
bool introspect_invoke_old(std::string path, const Poco::Net::HTMLForm &form)
{
    using namespace spin;

    // vars: request.getMethod(), form


    t_symbol *s = gensym(form["nodeID"].c_str());
    //ReferencedNode *n = dynamic_cast<ReferencedNode*>(gensym(form["nodeID"].c_str())->s_thing);
    std::string method = form["method"];



    if (s->s_thing)
    {

        cppintrospection::ValueList theArgs;
        cppintrospection::Value classInstance;
        if (s->s_type == REFERENCED_STATESET)
        {
            classInstance = cppintrospection::Value(dynamic_cast<ReferencedStateSet*>(s->s_thing));
        }
        else
        {
            classInstance = cppintrospection::Value(dynamic_cast<ReferencedNode*>(s->s_thing));
        }

        // the getInstanceType() method however, gives us the real type being pointed at:
        const cppintrospection::Type &classType = classInstance.getInstanceType();

        if (classType.isDefined())
        {
            std::cout << "introspection for: " << path << std::endl;
            introspect_print_type(classType);

            // TODO: update server state:
            Poco::Net::NameValueCollection::ConstIterator it;
            for (it = form.begin(); it != form.end(); ++it)
            {
                if ((it->first!="nodeID")&&(it->first!="method"))
                {
                    theArgs.push_back(it->second);
                }
            }

            // call method on class:
            // (the true means that it will try base classes as well)
            classType.invokeMethod(method, classInstance, theArgs, true);

            // debug:
            cppintrospection::ValueList debugArgs;
            //debugArgs.push_back("debug");
            cppintrospection::Value res = classType.invokeMethod("debug", classInstance, debugArgs, true);

            if (res.isEmpty() || res.isNullPointer())
            {
                std::cout << "error calling method" << std::endl;
            }
            else
            {
                std::cout << "success calling method" << std::endl;
                return true;
            }
        }
        else
        {
            std::cout << "ERROR: cound not process message '" << path << ". cppintrospection has no data for that node." << std::endl;
            return false;
        }
    }
    else
    {
        std::cout << "spinserver has no element at path: " << path << std::endl;
        return false;
    }


    return true;
}