int GitHubApiHelper::sendRequestAndProcess(HTTPClientSession &session,
                                           Poco::URI &uri,
                                           std::ostream &responseStream) {
  // create a request
  this->createRequest(uri);
  session.sendRequest(*m_request) << m_body;

  std::istream &rs = session.receiveResponse(*m_response);
  int retStatus = m_response->getStatus();
  g_log.debug() << "Answer from web: " << retStatus << " "
                << m_response->getReason() << "\n";

  if (retStatus == HTTP_OK ||
      (retStatus == HTTP_CREATED && m_method == HTTPRequest::HTTP_POST)) {
    Poco::StreamCopier::copyStream(rs, responseStream);
    processResponseHeaders(*m_response);
    return retStatus;
  } else if ((retStatus == HTTP_FORBIDDEN && isAuthenticated()) ||
             (retStatus == HTTP_UNAUTHORIZED) ||
             (retStatus == HTTP_NOT_FOUND)) {
    // If authentication fails you can get HTTP_UNAUTHORIZED or HTTP_NOT_FOUND
    // If the limit runs out you can get HTTP_FORBIDDEN
    return this->processAnonymousRequest(*m_response, uri, responseStream);
  } else if (isRelocated(retStatus)) {
    return this->processRelocation(*m_response, responseStream);
  } else {
    Poco::StreamCopier::copyStream(rs, responseStream);
    return processErrorStates(*m_response, rs, uri.toString());
  }
}
Beispiel #2
0
Poco::Net::HTTPClientSession* doHTTPIO(const Poco::URI& uri,
    const std::string& type, std::vector<HTTPHeader>* params,
    const char* reqBody, ulong size, const std::string& contentType) {
  HTTPClientSession *session = new HTTPClientSession(uri.getHost(),
      uri.getPort());
  HTTPRequest request(type, uri.getPathAndQuery());
  //Set Content size
  request.setContentLength(size);
  //Content Type
  if(contentType.length() != 0)
    request.setContentType(contentType);

  //Add params
  if (params != nullptr && params->size() > 0) {
    vector<HTTPHeader>::iterator it = params->begin();
    while (it != params->end()) {
      request.add(it->getKey(), it->getValue());
      it++;
    }
  }

  //write request body
  ostream &ostream = session->sendRequest(request);
  if (ostream == nullptr)
    return nullptr;
  ostream << reqBody;
  return session;
}
void InternetHelper::setupProxyOnSession(HTTPClientSession &session,
                                         const std::string &proxyUrl) {
  auto proxy = this->getProxy(proxyUrl);
  if (!proxy.emptyProxy()) {
    session.setProxyHost(proxy.host());
    session.setProxyPort(static_cast<Poco::UInt16>(proxy.port()));
  }
}
ofHttpResponse ofURLFileLoader::handleRequest(ofHttpRequest request) {
	try {
		URI uri(request.url);
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		HTTPResponse res;
		ofPtr<HTTPSession> session;
		istream * rs;
		if(uri.getScheme()=="https"){
			 //const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "rootcert.pem" ) );
			HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			httpsSession->setTimeout(Poco::Timespan(20,0));
			httpsSession->sendRequest(req);
			rs = &httpsSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpsSession);
		}else{
			HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
			httpSession->setTimeout(Poco::Timespan(20,0));
			httpSession->sendRequest(req);
			rs = &httpSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpSession);
		}
		if(!request.saveTo){
			return ofHttpResponse(request,*rs,res.getStatus(),res.getReason());
		}else{
			ofFile saveTo(request.name,ofFile::WriteOnly,true);
			char aux_buffer[1024];
			rs->read(aux_buffer, 1024);
			std::streamsize n = rs->gcount();
			while (n > 0){
				// we resize to size+1 initialized to 0 to have a 0 at the end for strings
				saveTo.write(aux_buffer,n);
				if (rs->good()){
					rs->read(aux_buffer, 1024);
					n = rs->gcount();
				}
				else n = 0;
			}
			return ofHttpResponse(request,res.getStatus(),res.getReason());
		}

	} catch (const Exception& exc) {
        ofLogError("ofURLFileLoader") << "handleRequest(): "+ exc.displayText();

        return ofHttpResponse(request,-1,exc.displayText());

    } catch (...) {
    	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
    }

	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
	
}	
Beispiel #5
0
Poco::Net::HTTPClientSession* doHTTPIO(const Poco::URI& uri,
    const std::string& type, std::vector<HTTPHeader>* params,
    std::ostream* &outputStream) {
  HTTPClientSession *session = new HTTPClientSession(uri.getHost(),
      uri.getPort());
  HTTPRequest request(type, uri.getPathAndQuery());

  //Add params
  if (params != nullptr && params->size() > 0) {
    vector<HTTPHeader>::iterator it = params->begin();
    while (it != params->end()) {
      request.add(it->getKey(), it->getValue());
      it++;
    }
  }

  //Ouput stream
  outputStream = &session->sendRequest(request);

  return session;
}
int InternetHelper::sendRequestAndProcess(HTTPClientSession &session,
                                          Poco::URI &uri,
                                          std::ostream &responseStream) {
  // create a request
  this->createRequest(uri);
  session.sendRequest(*m_request) << m_body;

  std::istream &rs = session.receiveResponse(*m_response);
  int retStatus = m_response->getStatus();
  g_log.debug() << "Answer from web: " << retStatus << " "
                << m_response->getReason() << std::endl;

  if (retStatus == HTTP_OK ||
      (retStatus == HTTP_CREATED && m_method == HTTPRequest::HTTP_POST)) {
    Poco::StreamCopier::copyStream(rs, responseStream);
    return retStatus;
  } else if (isRelocated(retStatus)) {
    return this->processRelocation(*m_response, responseStream);
  } else {
    Poco::StreamCopier::copyStream(rs, responseStream);
    return processErrorStates(*m_response, rs, uri.toString());
  }
}
Beispiel #7
0
void setSession(HTTPClientSession &session, string &host, Poco::UInt16 port )
{
    session.setHost(host);
    session.setPort(port);
}
Beispiel #8
0
int main(int argc, char **argv)
{

	string sha256("SHA256");
	Poco::Crypto::DigestEngine engine(sha256);
	engine.update("test");
	//string paylod_hash(engine.digest());
	Poco::DigestEngine::Digest paylod_hash = engine.digest();
	string payload((Poco::Crypto::DigestEngine::digestToHex(paylod_hash)));
	cout << payload << endl;

	//cout << paylod_hash << endl;




	 Document doc;
	 doc.SetObject();
	 Document::AllocatorType & allocator = doc.GetAllocator();

	 doc.AddMember("TableName", "patent", allocator);
	 doc.AddMember("ProjectionExpression", "patent_id", allocator);


	 //   doc.AddMember("")
	string body = doc2str(doc);

	string key_id("AKIAIDN3KXQXTMEGVLXA");
	string secret("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");
	{
		string method("POST");
		string service("dynamodb");
		string host("dynamodb.us-east-1.amazonaws.com");
		string uri("/");
		string region("us-east-1");
		string content_type("application/x-amz-json-1.0");
		string amz_target("DynamoDB_20120810.Scan");
		string query_string("");

		string amz_date = getAmzDate();
		string amz_stamp = getDateStamp(amz_date);


		string cannocial_header("");
		cannocial_header += "content-type:" + content_type + "\n" + \
				             "host:" + host + "\n" + \
				             "x-amz-date:" + amz_date + "\n" + \
				             "x-amz-target:" + amz_target + "\n";
		string signed_headers("content-type;host;x-amz-date;x-amz-target");



	}


    //cout << body << endl;

    //doc.AddMember("Limit", 1000, allocator);


    string dbHost("192.168.6.170");
    Poco::UInt16 dbPort(8000);

    HTTPClientSession session;
    setSession(session, dbHost, dbPort);

    HTTPRequest request;
    setRequestHeader(request);
    request.setContentLength(body.length());

    ostream & os =  session.sendRequest(request);
    os << body;

    HTTPResponse res;
    istream &is = session.receiveResponse(res);

    int statusCode = (int)res.getStatus();
    string status = res.getReason();
   // cout << status << endl;
  //  cout << statusCode << endl;

    string uuid_str;
    is >> uuid_str;
 //   cout << uuid_str << endl;

    //parse return
    Document uuid_doc;
    uuid_doc.Parse<0>(uuid_str.c_str());
    Value& uuids = uuid_doc["Items"];
    for(rapidjson::SizeType i = 0; i < uuids.Size();++i)
    {
        string id = uuids[i]["patent_id"]["S"].GetString();
        //cout << id << endl;
    }

 //   BSONBuilder buildObj;



//    string requestHeader  = string("host:") + dbHost + '\n';
 //   requestHeader += string("x-amz-date:") + getAmzDate() +'\n';
  //  requestHeader += string("x-amz-target:") + "DynamoDB_20120810.CreateTable" +"\n";

//    string requestStr = string("AWS4-HMAC-SHA256") + string("GET") +

    //HTTPRequest request(HTTPRequest::HTTP_POST, url.getPath(), HTTPRequest::HTTP_1_1);
}
bool ofxSimpleHttp::downloadURL(ofxSimpleHttpResponse* resp, bool sendResultThroughEvents, bool beingCalledFromMainThread, bool saveToDisk){

	bool ok;
	ofstream myfile;
	bool fileIsAlreadyHere = false;

	//create a file to save the stream to
	if(saveToDisk){

		if (resp->expectedChecksum.length()){ //if user provided a checksum
			ofFile f;
			f.open(resp->absolutePath);
			if (f.exists()){
				fileIsAlreadyHere = ofxChecksum::sha1(resp->absolutePath, resp->expectedChecksum);
				if(fileIsAlreadyHere){
					resp->checksumOK = true;
					resp->status = 0;
					resp->ok = true;
					resp->fileWasHere = true;
					ofLogVerbose() << "ofxSimpleHttp: about to download "<< resp->url << " but a file with same name and correct checksum is already here!";
					ofLogVerbose() << "ofxSimpleHttp: skipping download (" << resp->expectedChecksum << ")";
				}
			}
			f.close();
		}else{
			if (!onlySkipDownloadIfChecksumMatches){
				ofFile f;
				f.open(resp->absolutePath);
				if (f.exists() && f.getSize() > 0){
					resp->checksumOK = false;
					resp->status = 0;
					resp->ok = true;
					resp->fileWasHere = true;
					fileIsAlreadyHere = true;
					ofLogVerbose() << "ofxSimpleHttp: about to download "<< resp->url << " but a file with same name and (size > 0) is already here!";
					ofLogVerbose() << "ofxSimpleHttp: skipping download (missing checksum)";
				}
				f.close();
			}
		}
	}

	if (!fileIsAlreadyHere){ //if file is not here, download it!

		myfile.open( resp->absolutePath.c_str(), ios_base::binary );
		//myfile.open(ofToDataPath(filename).c_str()); //for not binary?

		try {

			ofHttpRequest request(resp->url, resp->url);
			URI uri(request.url);
			std::string path(uri.getPathAndQuery());
			if (path.empty()) path = "/";


			HTTPClientSession * session;

			if(uri.getScheme()=="https"){
				session = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			}else{
				session = new HTTPClientSession(uri.getHost(), uri.getPort());
			}

			//resp->session = &session;

			HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
			req.set( "User-Agent", userAgent.c_str() );

			session->setTimeout( Poco::Timespan(timeOut,0) );
			session->sendRequest(req);

			HTTPResponse res;
			istream& rs = session->receiveResponse(res);

			resp->status = res.getStatus();
			try {
				resp->timestamp = res.getDate();
			} catch (Exception& exc) {
				resp->timestamp = 0;
			}

			resp->reasonForStatus = res.getReasonForStatus( res.getStatus() );
			resp->contentType = res.getContentType();
			resp->serverReportedSize = res.getContentLength();
			resp->timeTakenToDownload = ofGetElapsedTimef();

			if (resp->serverReportedSize == -1) ofLogWarning("ofxSimpleHttp", "downloadURL(%s) >> Server doesn't report download size...", resp->fileName.c_str() );
			ofLogVerbose("ofxSimpleHttp", "downloadURL() >> about to start download (%s, %d bytes)", resp->fileName.c_str(), res.getContentLength() );
			ofLogVerbose("ofxSimpleHttp", "downloadURL() >> server reports request status: (%d-%s)", resp->status, resp->reasonForStatus.c_str() );

			//StreamCopier::copyStream(rs, myfile); //write to file here!
			if(saveToDisk){
				streamCopyWithProgress(rs, myfile, resp->serverReportedSize, resp->downloadProgress, resp->downloadSpeed, resp->downloadCanceled);
			}else{
				copyToStringWithProgress(rs, resp->responseBody, resp->serverReportedSize, resp->downloadProgress, resp->downloadSpeed, resp->downloadCanceled);
			}

			resp->timeTakenToDownload = ofGetElapsedTimef() - resp->timeTakenToDownload;
			if (resp->expectedChecksum.length() > 0){
				resp->checksumOK = ofxChecksum::sha1(resp->absolutePath, resp->expectedChecksum);
				if(!resp->checksumOK){
					ofLogVerbose() << "ofxSimpleHttp: downloaded OK but Checksum FAILED";
					ofLogVerbose() << "ofxSimpleHttp: SHA1 was meant to be: " << resp->expectedChecksum;
				}
			}

			resp->downloadSpeed = 0;
			resp->avgDownloadSpeed = 0;
			resp->downloadedBytes = 0;
			//resp->session = NULL;
			delete session;
			session = NULL;

			if(saveToDisk){
				myfile.close();
			}

			if (resp->downloadCanceled){
				//delete half-baked download file
				if (resp->downloadToDisk){
					ofFile f;
					if(f.open(resp->absolutePath)){
						if (f.isFile()){
							f.remove();
						}
					}
				}

			}else{

				if(saveToDisk){
					ofLogNotice("ofxSimpleHttp", "downloadURL() downloaded to %s", resp->fileName.c_str() );
				}

				if( saveToDisk ){
					//ask the filesystem what is the real size of the file
					ofFile file;
					try{
						file.open(resp->absolutePath.c_str());
						resp->downloadedBytes = file.getSize();
						file.close();
					}catch(Exception& exc){
						ofLogError("ofxSimpleHttp", "downloadURL(%s) >> Exception at file.open: %s", resp->fileName.c_str(), exc.displayText().c_str() );

					}
				}else{
					resp->downloadedBytes = resp->responseBody.size();
				}

				resp->avgDownloadSpeed = (resp->downloadedBytes / 1024.) / resp->timeTakenToDownload; //kb/sec


				//check download file size missmatch
				if ( resp->serverReportedSize > 0 && resp->serverReportedSize !=  resp->downloadedBytes) {

					ofLogWarning("ofxSimpleHttp", "downloadURLtoDiskBlocking() >> Download size mismatch (%s) >> Server: %d Downloaded: %d",
									 resp->fileName.c_str(), resp->serverReportedSize, resp->downloadedBytes );
					resp->reasonForStatus = "Download size mismatch!";
					resp->status = -1;
					resp->ok = false;

				}else{

					if (resp->status == 200){
						resp->ok = true;
					}else{
						resp->ok = false;
					}
				}

				ofLogVerbose() << "ofxSimpleHttp: download finished! " << resp->url << " !";
				ok = TRUE;

			}

		}catch(Exception& exc){

			myfile.close();
			ofLogError("ofxSimpleHttp", "downloadURL(%s) >> Exception: %s", resp->fileName.c_str(), exc.displayText().c_str() );
			resp->reasonForStatus = exc.displayText();
			resp->ok = false;
			resp->status = -1;
			ok = false;
			ofLogError() << "ofxSimpleHttp: failed to download " << resp->url << " !";
		}
	}

	//enqueue the operation result!
	if (sendResultThroughEvents ){

		if ( resp->notifyOnSuccess ){

			if(idleTimeAfterEachDownload > 0.0){
				ofSleepMillis(idleTimeAfterEachDownload * 1000);
			}

			if (beingCalledFromMainThread){ //we running on main thread, we can just snd the notif from here

				ofNotifyEvent( httpResponse, *resp, this );

			}else{ //we are running from a bg thread

				if (notifyFromMainThread){ //user wants to get notified form main thread, we need to enqueue the notification
					if (timeToStop == false){	//see if we have been destructed! dont forward events if so
						lock();
						ofxSimpleHttpResponse tempCopy = *resp;
						responsesPendingNotification.push(tempCopy);
						unlock();
					}
				}else{ //user doesnt care about main thread, the notificaiton can come from bg thread so we do it from here
					ofNotifyEvent( httpResponse, *resp, this );
				}
			}
		}
	}

	return ok;
}
Beispiel #10
0
// ----------------------------------------------------------------------
ofxHttpResponse ofxHttpUtils::getUrl(string url){

   ofxHttpResponse response;
   try{
		URI uri(url.c_str());
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);

		if(auth.getUsername()!="") auth.authenticate(req);

        if(sendCookies){
        	for(unsigned i=0; i<cookies.size(); i++){
        		NameValueCollection reqCookies;
        		reqCookies.add(cookies[i].getName(),cookies[i].getValue());
        		req.setCookies(reqCookies);
        	}
        }

		HTTPResponse res;
        ofPtr<HTTPSession> session;
        istream * rs;
        if(uri.getScheme()=="https"){
        	HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
        	httpsSession->setTimeout(Poco::Timespan(timeoutSeconds,0));
        	httpsSession->sendRequest(req);
        	rs = &httpsSession->receiveResponse(res);
        	session = ofPtr<HTTPSession>(httpsSession);
        }else{
        	HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
        	httpSession->setTimeout(Poco::Timespan(timeoutSeconds,0));
        	httpSession->sendRequest(req);
        	rs = &httpSession->receiveResponse(res);
        	session = ofPtr<HTTPSession>(httpSession);
        }

		response=ofxHttpResponse(res, *rs, url);

		if(sendCookies){
			cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end());
		}

		if(response.status>=300 && response.status<400){
			Poco::URI uri(req.getURI());
			uri.resolve(res.get("Location"));
			response.location = uri.toString();
		}

		ofNotifyEvent( newResponseEvent, response, this );

		//std::cout << res.getStatus() << " " << res.getReason() << std::endl;
		//StreamCopier::copyStream(rs, std::cout);

	}catch (Exception& exc){
		ofLogError("ofxHttpUtils") << exc.displayText();
        response.status = -1;
        response.reasonForStatus = exc.displayText();
    	ofNotifyEvent(newResponseEvent, response, this);
	}
	return response;

}
Beispiel #11
0
// ----------------------------------------------------------------------
ofxHttpResponse ofxHttpUtils::doPostForm(ofxHttpForm & form){
	ofxHttpResponse response;
    
    try{
        URI uri( form.action.c_str() );
        std::string path(uri.getPathAndQuery());
        if (path.empty()) path = "/";

        //HTTPClientSession session(uri.getHost(), uri.getPort());
		HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
		if(auth.getUsername()!="") auth.authenticate(req);

		if(sendCookies){
			for(unsigned i=0; i<cookies.size(); i++){
				NameValueCollection reqCookies;
				reqCookies.add(cookies[i].getName(),cookies[i].getValue());
				req.setCookies(reqCookies);
			}
		}

		for (unsigned int i = 0; i < form.headerIds.size(); ++i) {
			const std::string name = form.headerIds[i].c_str();
			const std::string val = form.headerValues[i].c_str();
			req.set(name, val);
		}


        HTTPResponse res;
		HTMLForm pocoForm;
		// create the form data to send
        if(form.formFiles.size()>0) {
			pocoForm.setEncoding(HTMLForm::ENCODING_MULTIPART);
        }
        else {
			pocoForm.setEncoding(HTMLForm::ENCODING_URL);
        }

		// form values
		for(unsigned i=0; i<form.formIds.size(); i++){
			const std::string name = form.formIds[i].c_str();
			const std::string val = form.formValues[i].c_str();
			pocoForm.set(name, val);
		}

		map<string,string>::iterator it;
		for(it = form.formFiles.begin(); it!=form.formFiles.end(); it++){
			string fileName = it->second.substr(it->second.find_last_of('/')+1);
			ofLogVerbose("ofxHttpUtils") << "adding file: " << fileName << " path: " << it->second;
			pocoForm.addPart(it->first,new FilePartSource(it->second));
		}

        pocoForm.prepareSubmit(req);

        ofPtr<HTTPSession> session;
        istream * rs;
        if(uri.getScheme()=="https"){
        	HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
        	httpsSession->setTimeout(Poco::Timespan(20,0));
            pocoForm.write(httpsSession->sendRequest(req));
        	rs = &httpsSession->receiveResponse(res);
        	session = ofPtr<HTTPSession>(httpsSession);
        }else{
        	HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
        	httpSession->setTimeout(Poco::Timespan(20,0));
            pocoForm.write(httpSession->sendRequest(req));
        	rs = &httpSession->receiveResponse(res);
        	session = ofPtr<HTTPSession>(httpSession);
        }

		response = ofxHttpResponse(res, *rs, form.action);

		if(sendCookies){
			cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end());
		}

		if(response.status>=300 && response.status<400){
			Poco::URI uri(req.getURI());
			uri.resolve(res.get("Location"));
			response.location = uri.toString();
		}

    	ofNotifyEvent(newResponseEvent, response, this);


    }catch (Exception& exc){
    	ofLogError("ofxHttpUtils") << "ofxHttpUtils error doPostForm -- " << form.action.c_str();
        
        //ofNotifyEvent(notifyNewError, "time out", this);

        // for now print error, need to broadcast a response
    	ofLogError("ofxHttpUtils") << exc.displayText();
        response.status = -1;
        response.reasonForStatus = exc.displayText();
    	ofNotifyEvent(newResponseEvent, response, this);

    }

    return response;
}
Beispiel #12
0
// ----------------------------------------------------------------------
ofxHttpResponse ofxHttpUtils::postData(string url, const ofBuffer & data,  string contentType){
	ofxHttpResponse response;
	try{
		URI uri( url.c_str() );
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		//HTTPClientSession session(uri.getHost(), uri.getPort());
		HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1);
		if(auth.getUsername()!="") auth.authenticate(req);

		if(sendCookies){
			for(unsigned i=0; i<cookies.size(); i++){
				NameValueCollection reqCookies;
				reqCookies.add(cookies[i].getName(),cookies[i].getValue());
				req.setCookies(reqCookies);
			}
		}

		if(contentType!=""){
			req.setContentType(contentType);
		}

		req.setContentLength(data.size());

		HTTPResponse res;
		ofPtr<HTTPSession> session;
		istream * rs;
		if(uri.getScheme()=="https"){
			HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			httpsSession->setTimeout(Poco::Timespan(20,0));
			httpsSession->sendRequest(req) << data;
			rs = &httpsSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpsSession);
		}else{
			HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
			httpSession->setTimeout(Poco::Timespan(20,0));
			httpSession->sendRequest(req) << data;
			rs = &httpSession->receiveResponse(res);
			session = ofPtr<HTTPSession>(httpSession);
		}

		response = ofxHttpResponse(res, *rs, url);

		if(sendCookies){
			cookies.insert(cookies.begin(),response.cookies.begin(),response.cookies.end());
		}

		if(response.status>=300 && response.status<400){
			Poco::URI uri(req.getURI());
			uri.resolve(res.get("Location"));
			response.location = uri.toString();
		}

		ofNotifyEvent(newResponseEvent, response, this);
	}catch (Exception& exc){

    	ofLogError("ofxHttpUtils") << "ofxHttpUtils error postData --";

        //ofNotifyEvent(notifyNewError, "time out", this);

        // for now print error, need to broadcast a response
    	ofLogError("ofxHttpUtils") << exc.displayText();
        response.status = -1;
        response.reasonForStatus = exc.displayText();
    	ofNotifyEvent(newResponseEvent, response, this);

    }
	return response;
}
Beispiel #13
0
SwiftResult<T>* doSwiftTransaction(Account *_account, std::string &_uriPath,
    const std::string &_method, std::vector<HTTPHeader>* _uriParams,
    std::vector<HTTPHeader>* _reqMap, std::vector<int> *_httpValidCodes,
    const char *bodyReqBuffer, ulong size, std::string *contentType) {
  //Start locking
  lock_guard<recursive_mutex> guard(transactionMutex);
  //Start of function
  if (_account == nullptr)
    return returnNullError<T>("account");
  Endpoint* swiftEndpoint = _account->getSwiftService()->getFirstEndpoint();
  if (swiftEndpoint == nullptr)
    return returnNullError<T>("SWIFT Endpoint");

  //Create parameter map
  vector<HTTPHeader> reqParamMap;
  //Add authentication token
  string tokenID = _account->getToken()->getId();
  HTTPHeader authHeader("X-Auth-Token", tokenID);
  reqParamMap.push_back(authHeader);
  //Add rest of request Parameters
  if (_reqMap != nullptr && _reqMap->size() > 0) {
    for (uint i = 0; i < _reqMap->size(); i++) {
      reqParamMap.push_back(_reqMap->at(i));
    }
  }

  URI uri(swiftEndpoint->getPublicUrl());
  string encoded;
  URI::encode(_uriPath,"",encoded);
  _uriPath = encoded;
  if (uri.getPath().size() > 0)
    uri.setPath(uri.getPath() + "/" + _uriPath);
  else
    uri.setPath(_uriPath);

  if (_uriParams != nullptr && _uriParams->size() > 0) {
    //Create appropriate URI
    ostringstream queryStream;
    //queryStream << "?";
    for (uint i = 0; i < _uriParams->size(); i++) {
      if (i > 0)
        queryStream << ",";
      queryStream << _uriParams->at(i).getQueryValue();
    }
    uri.setQuery(queryStream.str());
  }

  //Creating HTTP Session
  HTTPResponse *httpResponse = new HTTPResponse();
  HTTPClientSession *httpSession = nullptr;
  istream* resultStream = nullptr;

  try {
    /** This operation does not accept a request body. **/
    if (bodyReqBuffer == nullptr)
      httpSession = doHTTPIO(uri, _method, &reqParamMap);
    else {
      if (contentType != nullptr)
        httpSession = doHTTPIO(uri, _method, &reqParamMap, bodyReqBuffer, size,
            *contentType);
      else
        httpSession = doHTTPIO(uri, _method, &reqParamMap, bodyReqBuffer, size,"");
    }

    //Now we should increase number of calls to SWIFT API
    _account->increaseCallCounter();
    if (std::is_same<T, std::istream*>::value)
      resultStream = &httpSession->receiveResponse(*httpResponse);
    else
    	httpSession->receiveResponse(*httpResponse);
  } catch (Exception &e) {
    SwiftResult<T> *result = new SwiftResult<T>();
    SwiftError error(SwiftError::SWIFT_EXCEPTION, e.displayText());
    result->setError(error);
    //Try to set HTTP Response as the payload
    result->setSession(httpSession);
    result->setResponse(httpResponse);
    result->setPayload(nullptr);
    return result;
  }

  /**
   * Check HTTP return code
   */
  bool valid = false;
  for (uint i = 0; i < _httpValidCodes->size(); i++)
    if (_httpValidCodes->at(i) == httpResponse->getStatus()) {
      valid = true;
      break;
    }

  if (!valid) {
  	cout<<"Invalid Return code:";
    httpResponse->write(cout);
    if(httpResponse->getStatus() == 200)
    	cerr<<"bullshit"<<endl;
    if(httpResponse->getStatus() == HTTPResponse::HTTP_UNAUTHORIZED) {
      if(_account->reAuthenticate()) {
        delete httpSession;httpSession = nullptr;
        delete httpResponse;httpResponse = nullptr;
        return doSwiftTransaction<T>(_account, _uriPath,_method, _uriParams,
            _reqMap, _httpValidCodes, bodyReqBuffer, size, contentType);
      }
    }
    SwiftResult<T> *result = new SwiftResult<T>();
    string errorText = "Code:";
    errorText+= httpResponse->getStatus()+"\tReason:"+httpResponse->getReason();
    SwiftError error(SwiftError::SWIFT_HTTP_ERROR, errorText);
    result->setError(error);
    result->setSession(httpSession);
    result->setResponse(httpResponse);
    result->setPayload(nullptr);
    return result;
  }

  //Everything seems fine
  SwiftResult<T> *result = new SwiftResult<T>();
  result->setError(SWIFT_OK);
  result->setSession(httpSession);
  result->setResponse(httpResponse);
  result->setPayload((T)resultStream);
  //Cleanup
  return result;
}
void ofURLFileLoaderImpl::threadedFunction() {
	thread.setName("ofURLFileLoader " + thread.name());
	while( isThreadRunning() ){
		int cancelled;
		while(cancelRequestQueue.tryReceive(cancelled)){
			cancelledRequests.insert(cancelled);
		}
		ofHttpRequest request;
		if(requests.receive(request)){
			if(cancelledRequests.find(request.getID())==cancelledRequests.end()){
				ofHttpResponse response(handleRequest(request));
				int status = response.status;
#if __cplusplus>=201103
				if(!responses.send(move(response))){
#else
				if(!responses.send(response)){
#endif
					break;
				}
				if(status==-1){
					// retry
					requests.send(request);
				}
			}else{
				cancelledRequests.erase(cancelled);
			}
		}else{
			break;
		}
	}
}

ofHttpResponse ofURLFileLoaderImpl::handleRequest(ofHttpRequest request) {
	try {
		URI uri(request.url);
		std::string path(uri.getPathAndQuery());
		if (path.empty()) path = "/";

		HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
		HTTPResponse res;
		shared_ptr<HTTPSession> session;
		istream * rs;
		if(uri.getScheme()=="https"){
			 //const Poco::Net::Context::Ptr context( new Poco::Net::Context( Poco::Net::Context::CLIENT_USE, "", "", "rootcert.pem" ) );
			HTTPSClientSession * httpsSession = new HTTPSClientSession(uri.getHost(), uri.getPort());//,context);
			httpsSession->setTimeout(Poco::Timespan(20,0));
			httpsSession->sendRequest(req);
			rs = &httpsSession->receiveResponse(res);
			session = shared_ptr<HTTPSession>(httpsSession);
		}else{
			HTTPClientSession * httpSession = new HTTPClientSession(uri.getHost(), uri.getPort());
			httpSession->setTimeout(Poco::Timespan(20,0));
			httpSession->sendRequest(req);
			rs = &httpSession->receiveResponse(res);
			session = shared_ptr<HTTPSession>(httpSession);
		}
		if(!request.saveTo){
			return ofHttpResponse(request,*rs,res.getStatus(),res.getReason());
		}else{
			ofFile saveTo(request.name,ofFile::WriteOnly,true);
			char aux_buffer[1024];
			rs->read(aux_buffer, 1024);
			std::streamsize n = rs->gcount();
			while (n > 0){
				// we resize to size+1 initialized to 0 to have a 0 at the end for strings
				saveTo.write(aux_buffer,n);
				if (rs->good()){
					rs->read(aux_buffer, 1024);
					n = rs->gcount();
				}
				else n = 0;
			}
			return ofHttpResponse(request,res.getStatus(),res.getReason());
		}

	} catch (const Exception& exc) {
        ofLogError("ofURLFileLoader") << "handleRequest(): "+ exc.displayText();

        return ofHttpResponse(request,-1,exc.displayText());

    } catch (...) {
    	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
    }

	return ofHttpResponse(request,-1,"ofURLFileLoader: fatal error, couldn't catch Exception");
	
}	

void ofURLFileLoaderImpl::update(ofEventArgs & args){
	ofHttpResponse response;
	while(responses.tryReceive(response)){
		ofNotifyEvent(ofURLResponseEvent(),response);
	}

}
Beispiel #15
0
std::istream* HTTPStreamFactory::open(const URI& uri)
{
	poco_assert (uri.getScheme() == "http");

	URI resolvedURI(uri);
	URI proxyUri;
	HTTPClientSession* pSession = 0;
	HTTPResponse res;
	bool retry = false;
	bool authorize = false;
	std::string username;
	std::string password;

	try
	{
		do
		{
			if (!pSession)
			{
				pSession = new HTTPClientSession(resolvedURI.getHost(), resolvedURI.getPort());
			
				if (proxyUri.empty())
					pSession->setProxy(_proxyHost, _proxyPort);
				else
					pSession->setProxy(proxyUri.getHost(), proxyUri.getPort());
				pSession->setProxyCredentials(_proxyUsername, _proxyPassword);
			}
						
			std::string path = resolvedURI.getPathAndQuery();
			if (path.empty()) path = "/";
			HTTPRequest req(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
			
			if (authorize)
			{
				HTTPCredentials::extractCredentials(uri, username, password);
				HTTPCredentials cred(username, password);
				cred.authenticate(req, res);
			}
			
			pSession->sendRequest(req);
			std::istream& rs = pSession->receiveResponse(res);
			bool moved = (res.getStatus() == HTTPResponse::HTTP_MOVED_PERMANENTLY || 
						  res.getStatus() == HTTPResponse::HTTP_FOUND || 
						  res.getStatus() == HTTPResponse::HTTP_SEE_OTHER ||
						  res.getStatus() == HTTPResponse::HTTP_TEMPORARY_REDIRECT);
			if (moved)
			{
				resolvedURI.resolve(res.get("Location"));
				if (!username.empty())
				{
					resolvedURI.setUserInfo(username + ":" + password);
				}
				throw URIRedirection(resolvedURI.toString());
			}
			else if (res.getStatus() == HTTPResponse::HTTP_OK)
			{
				return new HTTPResponseStream(rs, pSession);
			}
			else if (res.getStatus() == HTTPResponse::HTTP_USEPROXY && !retry)
			{
				// The requested resource MUST be accessed through the proxy 
				// given by the Location field. The Location field gives the 
				// URI of the proxy. The recipient is expected to repeat this 
				// single request via the proxy. 305 responses MUST only be generated by origin servers.
				// only use for one single request!
				proxyUri.resolve(res.get("Location"));
				delete pSession; pSession = 0;
				retry = true; // only allow useproxy once
			}
			else if (res.getStatus() == HTTPResponse::HTTP_UNAUTHORIZED && !authorize)
			{
				authorize = true;
				retry = true;
				Poco::NullOutputStream null;
				Poco::StreamCopier::copyStream(rs, null);
			}
			else throw HTTPException(res.getReason(), uri.toString());
		}
		while (retry);
		throw HTTPException("Too many redirects", uri.toString());
	}
	catch (...)
	{
		delete pSession;
		throw;
	}
}