c++ - 使用 cpp-netlib 发送 HTTP POST 请求

标签 c++ httprequest cpp-netlib

已更新

我正在使用 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)
{
   ...
}

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

最佳答案

然后你应该添加如下内容:

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

否则你不要在任何地方指定 body。

编辑:也尝试添加类似的内容:

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

关于c++ - 使用 cpp-netlib 发送 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29006789/

相关文章:

c++ - 未在 html head 中指定时,如何使用 cpp-netlib 读取 UTF-8 编码

c++ - 在光线追踪器中计算阴影时出现意外结果

go - 如何有效地在 golang 中存储对文件的 html 响应

java - 解析从 Google 距离矩阵 API 发送的 Json 响应

c++ - 在 cpp-netlib http 服务器中访问请求 header

c++ - Boost 网络库在 MAC OSX 上无法识别

c++ - 在 macOS 上将 -fuse-ld=lld 与 Clang 一起使用

c++ - 对嵌套范围内经常重复出现的变量类型使用相同的名称

c++ - 将特定数组元素的地址传递给函数

java - Google App Engine 本地主机后端错误