【问题标题】:How to get json payload for a C++ json post如何获取 C++ json 帖子的 json 有效负载
【发布时间】:2013-02-19 15:23:27
【问题描述】:

我需要创建一个接受发布数据的 c++ cgi 应用程序。我将接受一个 json 对象。我如何获得有效载荷?

我可以使用下面的获取数据

int main() {
    bool DEBUG = true;

    cout << "content-type: text/html" << endl << endl;

    //WHAT GOES HERE FOR POST
    json=?????

    //THIS IS A GET
    query_string = getenv("QUERY_STRING");

}

【问题讨论】:

标签: c++ json http cgi


【解决方案1】:

如果方法类型是 POST(您可能还想检查一下),那么 POST 数据将写入标准输入。因此,您可以使用如下标准方法:

// Do not skip whitespace, more configuration may also be needed.
cin >> noskipws;

// Copy all data from cin, using iterators.
istream_iterator<char> begin(cin);
istream_iterator<char> end;
string json(begin, end);

// Use the JSON data somehow.
cout << "JSON was " << json << endl;

这会将 cin 中的所有数据读取到 json 中,直到出现 EOF。

【讨论】:

  • 不跳过空格的更简单方法是使用std::istreambuf_iterator
【解决方案2】:

假设 apache:

documentation is found here

您会在底部附近找到它,但发布数据是通过标准输入提供的。

#include <iostream>
#include <string>
#include <sstream>

int main() 
{   
    bool DEBUG = true;

    std::cout << "content-type: text/html\n\n"; // prefer \n\n to std::endl
                                                // you probably don't want to flush immediately.

    std::stringstream post;
    post << std::cin.rdbuf();

    std::cout << "Got: " << post.str() << "\n";
}   

【讨论】:

  • @Tampa:见上面的Olaf Dietsche cmets。他说它在 RFC 3875 中定义。所以可能。但是你应该阅读你的文档(或者只是尝试看看会发生什么)。
猜你喜欢
  • 2018-08-22
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
相关资源
最近更新 更多