1 #include "HttpConnection.hpp"
2 #include "JsonFormatter.hpp"
8 #include <Poco/StreamCopier.h>
9 #include <Poco/Net/HTTPResponse.h>
10 #include <Poco/Base64Encoder.h>
12 using namespace Poco::Net;
14 gde::HttpConnection::HttpConnection(Poco::URI uri, const Credentials& cred)
15 : _path("/"), _credentials(cred)
18 _session.setHost(uri.getHost());
19 _session.setPort(uri.getPort());
20 //_session.setProxy(machine, port);
21 } catch (Poco::Exception& e) {
22 std::cerr << e.displayText() << std::endl;
26 _path = uri.getPathAndQuery();
31 gde::HttpConnection::~HttpConnection()
36 // 1. request (json) --> CommandTO object
37 // 2. command data (json) from CommandTO --> <something>TO
38 // 3. call DAO with <something>TO and obtain another <something>TO
39 // 4. latter <something>TO --> (json) CommandResultTO data
40 // 5. set CommandResultTO code
41 // 6. CommandResultTO --> (json) response
44 gde::HttpConnection::_processRequest(const std::string& method,
47 int code = CommandResultTO::OK;
48 std::string message = "";
49 std::string data = "";
51 std::string requestBody = cto.toJson();
54 HTTPRequest request(method, _path, HTTPMessage::HTTP_1_1);
58 Poco::Base64Encoder b64enc(ss);
59 b64enc << _credentials.getLogin() << ":" << _credentials.getPassword(); // user::password
61 request.set("Authorization" , "Basic "+ss.str());
64 request.setContentLength(requestBody.length());
65 std::ostream& os = _session.sendRequest((HTTPRequest&)request);
66 // Send request body, if any
67 if (!requestBody.empty()) {
68 //std::istringstream iss(requestBody);
69 //Poco::StreamCopier::copyStream((std::istream&)iss, os);
74 HTTPResponse response;
75 std::istream& rs = _session.receiveResponse(response);
76 //std::cout << response.getStatus() << " " << response.getReason() << std::endl;
77 std::ostringstream responseBody;
78 Poco::StreamCopier::copyStream(rs, responseBody);
79 // responseBody contains a CommandResultTO in json format
80 return CommandResultTO::fromJson(responseBody.str());
81 } catch (Poco::Exception& e) {
82 std::cerr << e.displayText() << std::endl;
83 return CommandResultTO(CommandResultTO::ERROR);
88 gde::HttpConnection::doGet(const CommandTO& cto)
90 return _processRequest(HTTPRequest::HTTP_GET, cto);
94 gde::HttpConnection::doPost(const CommandTO& cto)
96 return _processRequest(HTTPRequest::HTTP_POST, cto);