Search code examples
c++httprequestcpp-netlib

Sending HTTP POST requests using cpp-netlib


UPDATED

I'm using cpp-netlib (v0.11.0) to send HTTP requests.

The following code sends an HTTP POST request with the given body.

client httpClient;

try
{
   uri::uri url;
   url << uri::scheme("http")
       << uri::host(m_hostname)
       << uri::port(m_port)
       << uri::path(m_path);

   // create a request instance and configure the headers
   client::request request(url);
   request << header("Connection", "close");
   request << header("Content-Type", "application/x-www-form-urlencoded");

   // send the request
   client::response response = httpClient.post(request, "foo=bar");
}

catch (std::exception& ex)
{
   ...
}

However, the following code results in a bad request.

client httpClient;

try
{
   uri::uri url;
   url << uri::scheme("http")
       << uri::host(m_hostname)
       << uri::port(m_port)
       << uri::path(m_path)
       << uri::query("foo", "bar");

  // create a request instance and configure the headers
   client::request request(url);
   request << header("Connection", "close");
   request << header("Content-Type", "application/x-www-form-urlencoded");
   request << body("foo=bar");

   // send the request
   client::response response = httpClient.post(request);
}

catch (std::exception& ex)
{
   ...
}

Please can someone explain what I'm doing wrong in the second example and which is the preferred option.


Solution

  • Then you should add something like:

    // ...
    request << header("Content-Type", "application/x-www-form-urlencoded");
    request << body("foo=bar");
    

    otherwise you don't specify body anywhere.

    EDIT: Also try adding something like:

    std::string body_str = "foo=bar";
    char body_str_len[8];
    sprintf(body_str_len, "%u", body_str.length());
    request << header("Content-Length", body_str_len);
    

    before

     request << body(body_str);