使用boost asio从http请求中读取JSON数据

时间:2017-05-28 13:52:47

标签: c++ json boost network-programming boost-asio

我正在尝试使用c ++服务器端的Boost ASIO从HTTP post请求接收JSON数据。我能够处理正常的HTTP请求但是我对如何读取发送到服务器的JSON数据毫无头绪。

我已经看过了:

BOOST ASIO POST HTTP REQUEST -- headers and body

How to send http request and retrieve a json response C++ Boost

HTTP POST request using boost::asio

Boost ASIO HTTP client POST

但是我不太了解在handle_request方法中读取特定JSON帖子的位置。我从Boost文档在线教程运行Boost ASIO服务器:http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/example/http/server/

由于我是网络编程的新手,请帮助我了解如何从前端HTTP请求中读取JSON数据(我已经找到了如何使用Boost属性树解析JSON数据)。

void request_handler::handle_request(const request& req, reply& rep)
{
  // Decode url to path.
  std::string request_path;
  if (!url_decode(req.uri, request_path))
  {
    rep = reply::stock_reply(reply::bad_request);
    return;
  }

  // Request path must be absolute and not contain "..".
  if (request_path.empty() || request_path[0] != '/'
      || request_path.find("..") != std::string::npos)
  {
    rep = reply::stock_reply(reply::bad_request);
    return;
  }

  vector<string> tokens=Utils::tokenizeString(request_path,"/");

  //token[0] is always request method
  if (tokens.size() == 0)
  {
      request_path += "index.html";
  }
  else if (tokens[0] == "getAllUsers")
  {
      rep = reply::stock_reply(reply::ok);
      return;
  }
  else if (tokens[0] == "getUser")
  {   
      //send ok response
      rep = reply::stock_reply(reply::ok);
      return;
  }
  else if (tokens[0] == "editUser")
  {
      //send ok response
      rep = reply::stock_reply(reply::ok);
      return;
  }

  // Determine the file extension.
  std::size_t last_slash_pos = request_path.find_last_of("/");
  std::size_t last_dot_pos = request_path.find_last_of(".");
  std::string extension;
  if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos)
  {
    extension = request_path.substr(last_dot_pos + 1);
  }

  // Open the file to send back.
  std::string full_path = doc_root_ + request_path;
  std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
  if (!is)
  {
      printf("file not found at %s\n",full_path.c_str());
    rep = reply::stock_reply(reply::not_found);
    return;
  }

  // Fill out the reply to be sent to the client.
  rep.status = reply::ok;
  char buf[512];
  while (is.read(buf, sizeof(buf)).gcount() > 0)
    rep.content.append(buf, is.gcount());
  rep.headers.resize(2);
  rep.headers[0].name = "Content-Length";
  rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
  rep.headers[1].name = "Content-Type";
  rep.headers[1].value = mime_types::extension_to_type(extension);
}

我想要实现的是从网站上获取每个方法的SQL查询参数:

  • getAllUsers
  • getUser:SELECT * FROM'table'WHER user_id = x
  • editUser:UPDATE'table'Set col1 ='val1,col2 ='val2',... WHERE id = x

进行数据库调用,并以JSON格式发送响应。

任何帮助将不胜感激!

0 个答案:

没有答案