bool FileDeleteHandler::isMyRequest(HttpRequest &hmsg){ // DELETE /files/'username'/'filename' quiere decir borrar archivo de tal usuario Server_Logger* log = Server_Logger::getInstance(); log->Log("Verifica que se trate de un Handler tipo FileDelete",INFO); if(hmsg.getUriParsedByIndex(0) == HttpRequest::FILES && hmsg.getUriCantCampos() == 3 && hmsg.getUriType() == HttpRequest::ELEMENT_URI && hmsg.getMethod() == HttpRequest::DELETE){ log->Log("Confirma que es un Handler tipo FileDelete",INFO); return true; } return false; }
bool SignUpHandler::isMyRequest(HttpRequest &hmsg){ // POST /users/ quiere decir sign up Server_Logger* log = Server_Logger::getInstance(); log->Log("Verifica que se trate de un Handler tipo SignUp",INFO); if(hmsg.getUriParsedByIndex(0) == HttpRequest::USERS && hmsg.getUriCantCampos() == 1 && hmsg.getUriType() == HttpRequest::COLLECTION_URI && hmsg.getMethod() == HttpRequest::POST){ log->Log("Confirma que es un Handler tipo SignUp",INFO); return true; } return false; }
bool UserModifyHandler::isMyRequest(HttpRequest &hmsg){ // PUT /users/'username' quiere decir modificar perfil de tal usuario Server_Logger* log = Server_Logger::getInstance(); log->Log("Verifica que se trate de un Handler tipo UserModify",INFO); if(hmsg.getUriParsedByIndex(0) == HttpRequest::USERS && hmsg.getUriCantCampos() == 2 && hmsg.getUriType() == HttpRequest::ELEMENT_URI && hmsg.getMethod() == HttpRequest::PUT){ log->Log("Confirma que es un Handler tipo UserModify",INFO); return true; } return false; }
bool FileAddHandler::isMyRequest(HttpRequest &hmsg){ // POST /files/'username'/ quiere decir subir archivo de tal usuario Server_Logger* log = Server_Logger::getInstance(); log->Log("Verifica que se trate de un Handler tipo FileAdd",INFO); if(hmsg.getUriParsedByIndex(0) == HttpRequest::FILES && hmsg.getUriCantCampos() == 2 && hmsg.getUriType() == HttpRequest::COLLECTION_URI && hmsg.getMethod() == HttpRequest::POST){ log->Log("Confirma que es un Handler tipo FileAdd",INFO); return true; } return false; }
bool RecyclebinGetHandler::isMyRequest(HttpRequest &hmsg){ // GET /files/'username'/recycle_bin/ devuelve los archivos de la recycle bin del usuario Server_Logger* log = Server_Logger::getInstance(); log->Log("Verifica que se trate de un Handler tipo RecycleBinGet",INFO); if (hmsg.getUriParsedByIndex(0) == HttpRequest::FILES && hmsg.getUriCantCampos() == 3 && hmsg.getUriParsedByIndex(2) == HttpRequest::RECYCLE_BIN && hmsg.getMethod() == HttpRequest::GET){ log->Log("Confirma que es un Handler tipo RecycleBinGet",INFO); return true; } return false; }
HttpRequest * HttpRequest::CreateRequest(const wchar_t * target, Method method, HttpRequestStatusListener * listener) { HttpRequest * req = PNEW HttpRequest(target, method, listener); req->Hold(); // One hold for TaskRunner() req->m_task = task_create(NULL, 0, TaskRunner, req, NULL, 0); return req; // Leave held. Caller should release // the request. }
bool_t BtceBtcUsd::process(Callback& callback) { HttpRequest httpRequest; Buffer data; String dataStr; for(;; Thread::sleep(14000)) { String url("https://btc-e.com/api/2/btc_usd/trades"); if(!httpRequest.get(url, data)) { error = httpRequest.getErrorString(); open = false; return false; } dataStr.attach((const char_t*)(byte_t*)data, data.size()); Variant dataVar; if(!Json::parse(dataStr, dataVar)) { error = "Could not parse trade data."; open = false; return false; } const List<Variant>& tradesList = dataVar.toList(); Trade trade; if(!tradesList.isEmpty()) { for(List<Variant>::Iterator i = --List<Variant>::Iterator(tradesList.end()), begin = tradesList.begin();; --i) { const HashMap<String, Variant>& tradeData = i->toMap(); trade.id = tradeData.find("tid")->toInt64(); int64_t timestamp = tradeData.find("date")->toInt64(); trade.time = timestamp * 1000LL; trade.price = tradeData.find("price")->toDouble(); trade.amount = tradeData.find("amount")->toDouble(); trade.flags = 0; if(trade.id > lastTradeId) { if(!callback.receivedTrade(trade)) return false; lastTradeId = trade.id; } if(i == begin) break; } } } return false; // unreachable }
// 发送HTTP请求 void HelloWorld::onHttpRequest(std::string type) { // 创建HTTP请求 HttpRequest* request = new HttpRequest(); if (type == "get") { request->setRequestType(HttpRequest::Type::GET); // url后面附加数据信息 request->setUrl("http://httpbin.org/get?name=hello&pwd=world"); } else if(type == "post") { request->setRequestType(HttpRequest::Type::POST); request->setUrl("http://httpbin.org/post"); // 设置post发送请求的数据信息 std::string data = "hello world!"; request->setRequestData(data.c_str(), data.length()); } // HTTP响应函数 request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpResponse, this)); // 发送请求 HttpClient::getInstance()->send(request); // 释放链接 request->release(); }
virtual void onHttpRequestContentCompleted(HttpRequest & request, AutoRef<DataSink> sink, HttpResponse & response) { cout << " ** path : " << request.getHeader().getPart2() << endl; if (request.getPath() == "/device.xml") { response.setStatus(200); response.setContentType("text/xml"); setFixedTransfer(response, dd(_udn)); } else if (request.getHeader().getPart2() == "/scpd.xml?udn=" + _udn + "&serviceType=" + dummy) { response.setStatus(200); response.setContentType("text/xml"); setFixedTransfer(response, scpd()); } else { response.setStatus(404); } }
void EventHandlerChecksAuthentication::_check_permission(HttpRequest &hmsg){ std::string username = hmsg.getUsername(); std::string token = hmsg.getConnToken(); Server_Logger* log = Server_Logger::getInstance(); log->Log("Se recibe la httprequest y se verifica token",INFO); log->Log("El username de la request es : "+username,DEBUG); log->Log("El token de la request es : "+username,DEBUG); // ver si no existen los campos (va, va a fallar la autenticacion si no) if(this->auth->isValidToken(username, token)){ this->_handle(hmsg); } else { hmsg.setResponse(Status::IOError("la token de autenticacion provista no es correcta")); } }
void HttpRequestManager::StopAllRequest() { FileLog("httprequest", "HttpRequestManager::StopAllRequest()"); HttpRequest *request = NULL; mKMutex.lock(); for(HttpRequestMap::iterator itr = mHttpRequestMap.begin(); itr != mHttpRequestMap.end(); itr++) { request = itr->second; if( request != NULL ) { request->StopRequest(); } } mKMutex.unlock(); }
void UserModifyHandler::_handle(HttpRequest &hmsg){ Status s; Server_Logger* log = Server_Logger::getInstance(); std::string username = hmsg.getUsername(); log->Log("El campo recibido por username es : "+username,DEBUG); if(username == ""){ hmsg.setResponse(Status::InvalidArgument()); return; } std::string email = hmsg.getCampo("email"); log->Log("El campo recibido por email es : "+email,DEBUG); std::string picture = hmsg.getCampo("picture"); log->Log("El campo recibido por picture es : "+picture,DEBUG); std::string place = hmsg.getCampo("place"); log->Log("El campo recibido por place es : "+place,DEBUG); std::string name = hmsg.getCampo("name"); log->Log("El campo recibido por name es : "+name,DEBUG); UserMetadata user_metadata(db); user_metadata.setUsername(username); // tal vez cambiar a ModifyUser como con los archivos s = user_metadata.DBchange_email(email); if (s.ok()) s = user_metadata.DBchange_profile_pic(picture); if (s.ok()) s = user_metadata.DBchange_last_place(place); if (s.ok()) s = user_metadata.DBchange_name(name); // ver status if(s.ok()){ hmsg.setResponse(s, "Changes saved"); } else { hmsg.setResponse(s); } }
static Aws::String CanonicalizeRequestSigningString(HttpRequest& request, bool urlEscapePath) { request.CanonicalizeRequest(); Aws::StringStream signingStringStream; signingStringStream << HttpMethodMapper::GetNameForHttpMethod(request.GetMethod()); //double encode paths unless explicitly stated otherwise (for s3 compatibility) URI uriCpy = request.GetUri(); uriCpy.SetPath(uriCpy.GetURLEncodedPath()); signingStringStream << NEWLINE << (urlEscapePath ? uriCpy.GetURLEncodedPath() : uriCpy.GetPath()) << NEWLINE; if (request.GetQueryString().size() > 1 && request.GetQueryString().find("=") != std::string::npos) { signingStringStream << request.GetQueryString().substr(1) << NEWLINE; } else if (request.GetQueryString().size() > 1) { signingStringStream << request.GetQueryString().substr(1) << "=" << NEWLINE; } else { signingStringStream << NEWLINE; } return signingStringStream.str(); }
void Network::IsReachable(const String& hostAddr) { String* pProxyAddr = null; //String hostAddr = L"http://localhost:port"; AppLogDebug("Trying to reach...%S", hostAddr.GetPointer()); __pHttpSession = new HttpSession(); __pHttpSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, pProxyAddr, hostAddr, null); HttpTransaction* pHttpTransaction = __pHttpSession->OpenTransactionN(); pHttpTransaction->AddHttpTransactionListener(*this); HttpRequest* pHttpRequest = pHttpTransaction->GetRequest(); pHttpRequest->SetMethod(NET_HTTP_METHOD_GET); pHttpRequest->SetUri(hostAddr); pHttpTransaction->Submit(); }
void JsHttpRequestProcessor::GetPath(Local<String> name, const PropertyCallbackInfo<Value>& info) { // Extract the C++ request object from the JavaScript wrapper. HttpRequest* request = UnwrapRequest(info.Holder()); // Fetch the path. const string& path = request->Path(); // Wrap the result in a JavaScript string and return it. info.GetReturnValue().Set( String::NewFromUtf8(info.GetIsolate(), path.c_str(), NewStringType::kNormal, static_cast<int>(path.length())).ToLocalChecked()); }
bool WinSyncHttpClient::StreamPayloadToRequest(const HttpRequest& request, void* hHttpRequest) const { bool success = true; auto payloadStream = request.GetContentBody(); if(payloadStream) { auto startingPos = payloadStream->tellg(); char streamBuffer[ HTTP_REQUEST_WRITE_BUFFER_LENGTH ]; bool done = false; while(success && !done) { payloadStream->read(streamBuffer, HTTP_REQUEST_WRITE_BUFFER_LENGTH); std::streamsize bytesRead = payloadStream->gcount(); success = !payloadStream->bad(); uint64_t bytesWritten = 0; if (bytesRead > 0) { bytesWritten = DoWriteData(hHttpRequest, streamBuffer, bytesRead); if (!bytesWritten) { success = false; } } auto& sentHandler = request.GetDataSentEventHandler(); if (sentHandler) { sentHandler(&request, (long long)bytesWritten); } if(!payloadStream->good()) { done = true; } success = success && IsRequestProcessingEnabled(); } payloadStream->clear(); payloadStream->seekg(startingPos, payloadStream->beg); } if(success) { success = DoReceiveResponse(hHttpRequest); } return success; }
// {{{ UrlFetcher impl // }}} // {{{ Imageable impl void Imageable::wandError() { ExceptionType severity; char* description = MagickGetException(wand_, &severity); request_->log(Severity::error, "%s %s %lu %s\n", GetMagickModule(), description); MagickRelinquishMemory(description); request_->status = HttpStatus::InternalServerError; request_->finish(); delete this; }
void UserManagementAPI::handleUserSignupPost(HttpRequest &request, HttpResponse &response) { QByteArray rawData = request.getRawData(); QJsonParseError error; QJsonDocument data = QJsonDocument::fromJson(rawData, &error); if (error.error != QJsonParseError::NoError) { respondJsonParseError(response, error); return; } QJsonObject dataObject = data.object(); if (dataObject.contains("email") && dataObject.contains("password") && dataObject.contains("g_recaptcha_response")) { QString email = dataObject["email"].toString(); QByteArray password = dataObject["password"].toString().toLatin1(); QString g_recaptcha_response = dataObject["g_recaptcha_response"].toString(); if (!ReCAPTCHAVerifier::getSingleton().verify(g_recaptcha_response, request.getFromIPAddress())) { respond(response, StatusCode::reCAPTCHAFailed, "reCAPTCHA check failed!"); return; } QHash<QString, QVariant> extraFields; QString errorMessage; QByteArray activationCode; if(m_userManager.signup(email, password, extraFields, errorMessage, activationCode)) { if (sendActivationEmail(email, QString::fromLatin1(activationCode))) { respondSuccess(response); } else { respond(response, StatusCode::SendActivationEmailFailed, "failed to send activation email!"); } } else { respond(response, StatusCode::SignupFailed, "Signup failed: " % errorMessage); } } else { respondParameterMissing(response); } }
void onRequest(HttpRequest const& req, HttpResponse& resp) { //std::cout << "Headers " << req.methodString() << " " << req.path() << std::endl; if (!benchmark) { const std::map<string, string>& headers = req.getHeaders(); for (std::map<string, string>::const_iterator it = headers.begin(); it != headers.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } } if (req.getPath() == "/") { resp.setStatusCode(HttpResponse::HttpStatusCode::k200Ok); resp.setStatusMessage("OK"); resp.setContentType("text/html"); resp.setHeader("Server", "Muduo"); string now = Timestamp::now().toFormattedString(); resp.setBody("<html><head><title>This is title</title></head>" "<body><h1>Hello</h1>Now is " + now + "</body></html>"); } else if (req.getPath() == "/hello") { resp.setStatusCode(HttpResponse::HttpStatusCode::k200Ok); resp.setStatusMessage("OK"); resp.setContentType("text/plain"); resp.setHeader("Server", "Muduo"); resp.setBody("hello, world!\n"); } else if (req.getPath() == "/angel") { resp.setStatusCode(HttpResponse::HttpStatusCode::k200Ok); resp.setStatusMessage("OK"); resp.setContentType("text/plain"); resp.setHeader("Server", "Muduo"); resp.setBody("hello, angel!\n"); } else { resp.setStatusCode(HttpResponse::HttpStatusCode::k404NotFound); resp.setStatusMessage("Not Found"); resp.setCloseConnection(true); } }
unsigned long HttpRequestManager::StartRequest(string path, HttpEntiy& entiy, IHttpRequestManagerCallback* callback, SiteType type, bool bNoCache) { FileLog("httprequest", "HttpRequestManager::StartRequest( " "path : %s, " "entiy : %p, " "callback : %p )", path.c_str(), &entiy, callback ); long requestId = 0; string host = mHttpRequestHostManager->GetHostByType(type); // 配置http用户认证 entiy.SetAuthorization(mUser, mPassword); // 配置客户端版本 entiy.AddHeader(mVersionKey, mVersionCode); // FileLog("httprequest", "HttpRequestManager::StartRequest() request lock begin, path:%s", path.c_str()); mKMutex.lock(); // FileLog("httprequest", "HttpRequestManager::StartRequest() request lock ok, path:%s", path.c_str()); HttpRequest *request = new HttpRequest(); request->SetCallback(this); request->SetNoCacheData(bNoCache); requestId = request->StartRequest(host, path, entiy); FileLog("httprequest", "HttpRequestManager::StartRequest( " "requestId : %ld, " "path : %s " ") ", requestId, path.c_str() ); mHttpRequestMap.insert(HttpRequestMap::value_type(requestId, request)); if( callback != NULL ) { mIHttpRequestManagerCallbackMap.insert(IHttpRequestManagerCallbackMap::value_type(requestId, callback)); } // FileLog("httprequest", "HttpRequestManager::StartRequest() request lock finish, path:%s", path.c_str()); mKMutex.unlock(); // FileLog("httprequest", "HttpRequestManager::StartRequest() request unlocked, path:%s", path.c_str()); return requestId; }
void RssCommandsApiController::service(HttpRequest& request, HttpResponse& response) { if (!CheckCreditinals(request, response)) { return; } QString method = request.getMethod(); if (method.compare("post", Qt::CaseInsensitive) == 0) { QString feedId = request.getParameter("feedId"); #ifdef Q_WS_WIN feedId = QString("{%1}").arg(feedId); #endif QUuid uid(feedId); QString action = request.getParameter("action"); RssFeed* pFeed = m_pRssManager->findFeed(uid); if (pFeed != NULL) { if (action.compare("remove", Qt::CaseInsensitive) == 0) { //QEventLoop loop; if (!QMetaObject::invokeMethod(m_pRssManager.get(), "removeFeed", Qt::QueuedConnection, Q_ARG(QUuid, uid))) { qWarning() << "QMetaObject::invokeMethod removeFeed failed"; } //m_pRssManager->removeFeed(uid); } else if (action.compare("downloadItem", Qt::CaseInsensitive) == 0) { } } else { response.setStatus(404, "Not Found"); response.write("<BODY><h3>404 RSS Feed not found.</h3>"); response.write("</BODY>"); } } else { response.setStatus(405, "Method Not Allowed"); response.write("<BODY><h3>405 Method Not Allowed.</h3>"); response.write("</BODY>"); } }
void onLcd(HttpRequest &request, HttpResponse &response) { int y = request.getQueryParameter("y").toInt(); String text = request.getQueryParameter("text"); setLcd(y, text); JsonObjectStream* stream = new JsonObjectStream(); JsonObject& json = stream->getRoot(); json["status"] = (bool)true; response.setAllowCrossDomainOrigin("*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Request, X-Request, X-Requested-With"); response.sendJsonObject(stream); }
void UserManagementAPI::handleGitHubRegisterGet(HttpRequest &request, HttpResponse &response) { const QHash<QString, QSharedPointer<QString>> &queries = request.getHeader().getQueries(); QString code; if (!queries.contains("code")) { respond(response, StatusCode::MissingParameters, "no code"); } code = *queries["code"].data(); QString client_id = SettingsManager::getSingleton().get("GitHub/client_id").toString(); QString client_secret = SettingsManager::getSingleton().get("GitHub/client_secret").toString(); QUrl verificationUrl = QUrl("https://github.com/login/oauth/access_token"); QUrlQuery query; query.addQueryItem("code", code); query.addQueryItem("client_id", client_id); query.addQueryItem("client_secret", client_secret); verificationUrl.setQuery(query.query()); QNetworkRequest gitHubRequest; gitHubRequest.setUrl(verificationUrl); QByteArray replyData; m_networkServiceAccessor.post(gitHubRequest, QByteArray(), replyData); respondSuccess(response); }
bool HttpServer::initWebSocket(HttpServerConnection& connection, HttpRequest& request, HttpResponse& response) { if (!wsEnabled) return false; WebSocket *sock = new WebSocket(&connection); if (!sock->initialize(request, response)) return false; connection.setTimeOut(USHRT_MAX); //Disable disconnection on connection idle (no rx/tx) connection.setDisconnectionHandler(HttpServerConnectionDelegate(&HttpServer::onCloseWebSocket, this)); // auto remove on close response.sendHeader(connection); // Will push header before user data wsocks.addElement(sock); if (wsConnect) wsConnect(*sock); if (wsCommandEnabled && (request.getQueryParameter(wsCommandRequestParam) == "true")) { #if ENABLE_CMD_EXECUTOR debugf("WebSocket Commandprocessor started"); #else debugf("WebSocket Commandprocessor support DISABLED via ENABLE_CMD_EXECUTOR"); #endif sock->enableCommand(); } }
HttpRequest* Mx::send(const char* url, HttpRequest::Type type, bool isImmediate, const ccHttpRequestCallback& callback){ HttpRequest* request = new HttpRequest(); request->setUrl(url); request->setRequestType(HttpRequest::Type::GET); request->setResponseCallback(callback); if (isImmediate) { HttpClient::getInstance()->sendImmediate(request); }else { HttpClient::getInstance()->send(request); } request->release(); return request; }
void UserManagementAPI::handleUserLogoutPost(HttpRequest &request, HttpResponse &response) { QByteArray rawData = request.getRawData(); QJsonParseError error; QJsonDocument data = QJsonDocument::fromJson(rawData, &error); if (error.error != QJsonParseError::NoError) { respondJsonParseError(response, error); return; } QJsonObject dataObject = data.object(); if (dataObject.contains("session_id")) { QByteArray session_id = dataObject["session_id"].toString().toLatin1(); if (!m_sessionManager.logoutSession(session_id)) { respond(response, StatusCode::LogoutFailed, "Logout failed."); } else { respondSuccess(response); } } else { respondParameterMissing(response); } }
void onState(HttpRequest &request, HttpResponse &response) { //systemTime = SystemClock.getSystemTimeString(); int freq = request.getQueryParameter("value").toInt(); JsonObjectStream* stream = new JsonObjectStream(); JsonObject& json = stream->getRoot(); json["status"] = (bool)true; // String timeString = json["time"] = SystemClock.now().toUnixTime();; json["mute"] = mute; json["source"] = source; json["mixing"] = mixing; json["enhance"] = enhance; json["volumeFR"] = 74-volumeFR; json["volumeFL"] = 74-volumeFL; json["volumeRR"] = 74-volumeRR; json["volumeRL"] = 74-volumeRL; json["volumeCEN"] = 74-volumeCEN; json["volumeSW"] = 74-volumeSW; json["frequency"] = frequency; json["volumeALLCH"] = 74-volumeALLCH; json["power"] = power; response.setAllowCrossDomainOrigin("*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Request, X-Request, X-Requested-With"); response.sendJsonObject(stream); }
void ScopeManager::setSessionId(HttpRequest& request, const std::string& sessionId) { if (sessionId.empty()) { request.setSessionScope(0); } else { Sessionscope* sessionScope = getSessionScope(sessionId); if (sessionScope != 0) { log_debug("session found"); request.setSessionScope(sessionScope); } } }
Dictionary::Ptr HttpUtility::FetchRequestParameters(HttpRequest& request) { Dictionary::Ptr result; String body; char buffer[1024]; size_t count; while ((count = request.ReadBody(buffer, sizeof(buffer))) > 0) body += String(buffer, buffer + count); if (!body.IsEmpty()) { #ifdef I2_DEBUG Log(LogDebug, "HttpUtility") << "Request body: '" << body << "'"; #endif /* I2_DEBUG */ result = JsonDecode(body); } if (!result) result = new Dictionary(); typedef std::pair<String, std::vector<String> > kv_pair; for (const kv_pair& kv : request.RequestUrl->GetQuery()) { result->Set(kv.first, Array::FromVector(kv.second)); } return result; }
void CDropbox::DestroyAcceessToken() { HttpRequest *request = new HttpRequest(hNetlibUser, REQUEST_POST, DROPBOX_API_URL "/disable_access_token"); mir_ptr<NETLIBHTTPREQUEST> response(request->Send()); delete request; MCONTACT hContact = CDropbox::GetDefaultContact(); db_unset(NULL, MODULE, "TokenSecret"); if (hContact) { if (db_get_w(hContact, MODULE, "Status", ID_STATUS_ONLINE) == ID_STATUS_ONLINE) db_set_w(hContact, MODULE, "Status", ID_STATUS_OFFLINE); } }