0

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.

ksl
  • 4,519
  • 11
  • 65
  • 106

1 Answers1

4

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);
tonso
  • 1,760
  • 1
  • 11
  • 19
  • OK I see that I need to add the body to the request. However, that still doesn't work. – ksl Mar 12 '15 at 11:01
  • @ksl I expanded my post – tonso Mar 12 '15 at 11:57
  • Thanks @id256. That was it. I'd like to send multiple values - do you know if I have to format the key-value pairs myself (i.e. separate each with a '&') or is there a function to do it for me? – ksl Mar 12 '15 at 14:12
  • I'd use `std::accumulate` function from STL `algorithm` passing an instance of something like `struct append_fun { std::string operator()(const std::string& s1, const std::string& s2) { return s1+"&"+s2; } }` as `BinaryOperation` parameter. – tonso Mar 12 '15 at 14:22