Last active
February 9, 2023 03:36
-
-
Save jeffcrouse/247717dcca0669090cfa 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); | |
} |
Can headers be set when using httpstreamfactory?
Thank you
Exactly what I was looking for, thanks!
Please check my question at below link and help
https://stackoverflow.com/questions/50210371/cpp-clients-to-maintain-http-session-id-and-reuse-for-every-interaction
very helpful, thanks! Remember if its an HTTPS session you will need to use HTTPSClientSession session(uri.getHost(), uri.getPort());
and initialize SSL.
Thanks, man. You helped me a lot.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks. Was looking for a simple demo showing the setting of headers using POCO. Clear enough!