Skip to content

Instantly share code, notes, and snippets.

@jeffcrouse
Last active February 9, 2023 03:36
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jeffcrouse/247717dcca0669090cfa to your computer and use it in GitHub Desktop.
Save jeffcrouse/247717dcca0669090cfa to your computer and use it in GitHub Desktop.
Poco HTTPPOST request with headers
#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 = "username=user1@yourdomain.com&password=mypword";
map<string,string> headers;
headers["Test-Header"] = "Rainbow Lollipop";
ofLogNotice() << ofPostRequest("http://localhost:8080", body, headers);
}
@richsad
Copy link

richsad commented Jul 23, 2015

thanks. Was looking for a simple demo showing the setting of headers using POCO. Clear enough!

@EaswarAiyer
Copy link

Can headers be set when using httpstreamfactory?

@zerojiu
Copy link

zerojiu commented Dec 6, 2016

Thank you

@dpanzer
Copy link

dpanzer commented Feb 2, 2018

Exactly what I was looking for, thanks!

@balamcsd
Copy link

balamcsd commented May 7, 2018

@iquestor
Copy link

very helpful, thanks! Remember if its an HTTPS session you will need to use HTTPSClientSession session(uri.getHost(), uri.getPort());
and initialize SSL.

@wuyongf
Copy link

wuyongf commented Jun 15, 2020

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