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.

2
  • So you want to send a request with empty body? Commented Mar 12, 2015 at 10:40
  • No, I want the body to be "foo=bar". Why do you ask that? Commented Mar 12, 2015 at 10:43

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

OK I see that I need to add the body to the request. However, that still doesn't work.
@ksl I expanded my post
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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.