How do I make an HTTP Post with HTTP Basic Authentication, using POCO?

Alyoshak picture Alyoshak · Oct 31, 2012 · Viewed 12.4k times · Source

I'm trying to make an HTTP Post with HTTP Basic Authentication (cleartext username and password), using POCO. I found an example of a Get and have tried to modify it, but being a rookie I think I've mangled it beyond usefulness. Anyone know how to do this?

Yes, I've already seen the other SO question on this: POCO C++ - NET SSL - how to POST HTTPS request, but I can't make sense of how it is trying to implement the username and password part. I also don't understand the use of "x-www-form-urlencoded". Is this required for a Post? I don't have a form. Just want to POST to the server with username and password parameters.

Answer

Alyoshak picture Alyoshak · Nov 5, 2012

Finally. Here's how you do it:

HTTPClientSession session("yourdomain.com");
session.setKeepAlive(true);

Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, "/myapi.php/api/validate", HTTPMessage::HTTP_1_1);
req.setContentType("application/x-www-form-urlencoded");
req.setKeepAlive(true); // notice setKeepAlive is also called on session (above)

std::string reqBody("[email protected]&password=mypword");
req.setContentLength( reqBody.length() );

std::ostream& myOStream = session.sendRequest(req); // sends request, returns open stream
myOStream << reqBody;  // sends the body

req.write(std::cout);

Poco::Net::HTTPResponse res;
std::istream& iStr = session.receiveResponse(res);  // get the response from server
std::cerr << iStr.rdbuf();  // dump server response so you can view it