-
-
Save timonsku/4ca8dffba4dc4c094de22eb295738499 to your computer and use it in GitHub Desktop.
Poco HTTPPOST request with headers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Poco/Net/HTTPClientSession.h> | |
#include <Poco/Net/HTTPRequest.h> | |
#include <Poco/Net/HTTPResponse.h> | |
#include <Poco/StreamCopier.h> | |
#include <Poco/Path.h> | |
#include <Poco/URI.h> | |
#include <Poco/Exception.h> | |
using namespace Poco::Net; | |
using namespace Poco; | |
string ofPostRequest(string url, string body, map<string,string> headers) { | |
try | |
{ | |
// prepare session | |
URI uri(url); | |
HTTPClientSession session(uri.getHost(), uri.getPort()); | |
// prepare path | |
string path(uri.getPathAndQuery()); | |
if (path.empty()) path = "/"; | |
// send request | |
HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_1); | |
req.setContentType("application/x-www-form-urlencoded"); | |
// Set headers here | |
for(map<string,string>::iterator it = headers.begin(); | |
it != headers.end(); it++) { | |
req.set(it->first, it->second); | |
} | |
// Set the request body | |
req.setContentLength( body.length() ); | |
// sends request, returns open stream | |
std::ostream& os = session.sendRequest(req); | |
os << body; // sends the body | |
//req.write(std::cout); // print out request | |
// get response | |
HTTPResponse res; | |
cout << res.getStatus() << " " << res.getReason() << endl; | |
istream &is = session.receiveResponse(res); | |
stringstream ss; | |
StreamCopier::copyStream(is, ss); | |
return ss.str(); | |
} | |
catch (Exception &ex) | |
{ | |
cerr << ex.displayText() << endl; | |
return ""; | |
} | |
} | |
//-------------------------------------------------------------- | |
void ofApp::setup(){ | |
string body = "[email protected]&password=mypword"; | |
map<string,string> headers; | |
headers["Test-Header"] = "Rainbow Lollipop"; | |
ofLogNotice() << ofPostRequest("http://localhost:8080", body, headers); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment