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

好久不见. 提交于 2019-12-03 08:57:01

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("username=user1@yourdomain.com&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

When you do an HTTP POST, typically the data that is being sent to the server is sent in one of two forms:

  • Name,Value pairs where the name and value are separated by "=", and distinct pairs are separated by "&". For example: var1=value1&var2=value2. Also, these name value pairs are sent so that certain special characters and non-alphanumeric characters are replaced by %HH, a percent sign and two hexadecimal digits representing the ASCII code of the character. For example, if value for the first parameter included an "#", it would be sent as var1=value1%23&var2=value2. When sending data in this format, the client is required to insert a Content-Type header with the value application/x-www-form-urlencoded so that the server may be able to decode the data correctly.

  • As a multipart MIME body where each part can be large in size as well as include "non-escaped" data (including binary data). Different MIME parts are separated by a string delimiter (boundary) that does not appear within any of the MIME "payloads". When sending data in this format, the client is required to insert a Content-Type header with the value multipart/form-data.

In the case of the previous StackOverflow question you referenced, the request body is being sent in the first manner as shown above. Hope that clarifies.

Regards, Siddharth

From the POCO library credential test, here is the code:

HTTPRequest request;
assert (!request.hasCredentials());

HTTPBasicCredentials cred("user", "secret");
cred.authenticate(request);
assert (request.hasCredentials());
std::string scheme;
std::string info;
request.getCredentials(scheme, info);
assert (scheme == "Basic");
assert (info == "dXNlcjpzZWNyZXQ=");

HTTPBasicCredentials cred2(request);
assert (cred2.getUsername() == "user");
assert (cred2.getPassword() == "secret");

When sending the request, you would only use the first part of this code (stopping at cred.authenticate(request)).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!