0

更新

我正在使用 cpp-netlib (v0.11.0) 发送 HTTP 请求。

以下代码使用给定的正文发送 HTTP POST 请求。

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)
{
   ...
}

但是,以下代码会导致错误请求。

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)
{
   ...
}

请有人可以解释我在第二个示例中做错了什么,哪个是首选选项。

4

1 回答 1

4

然后你应该添加类似的东西:

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

否则你不会在任何地方指定正文。

编辑:也尝试添加类似的东西:

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);

 request << body(body_str);
于 2015-03-12T10:44:43.983 回答