使用cpprest-sdk与json服务发布POST问题,连接到jeasyui

时间:2017-01-23 21:12:48

标签: json jeasyui cpprest-sdk

我正在开发一个Web服务来将json对象提供给jeasyui异步树。我的HTML有以下内容:

<ul id="tt" method="POST" class="easyui-tree" url="http://w.x.y.z:1024/testrest">
</ul>

假设w.x.y.z是我服务器的IP地址。根据他们的PHP json服务的jeasyui文档,我需要返回一个包含密钥idtextstate的字典对象数组。好的,到目前为止一切顺利。我正在尝试使用Microsoft的cpprest-sdk在c ++中开发json服务。我在RHEL 7.2上编译并安装了这个库,并且能够使用它编写一些基本服务。问题在于(我认为)json的编码被发送回客户端。

这是一个功能齐全的示例json服务器,使用cpprest-sdk编写,处理POST请求并使用符合jeasyui预期协议的单个填充的字典对象数组进行回复:

#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#pragma comment(lib, "cpprestlib" )

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;

#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;

#define TRACE(msg)            wcout << msg 

void handle_request(http_request request, function<void(const json::value &, json::value &, bool)> action)
{
    json::value answer;

    TRACE("\nHandle_request\n");

    // Spit out the HTTP header to the console...
    const auto HeaderString = request.to_string();
    wcout << HeaderString.c_str() << endl;

    request
        .extract_json()
        .then([&answer, &action](pplx::task<json::value> task) {
            try
            {
                const auto & jvalue = task.get();
                if (!jvalue.is_null())
                {
                    action(jvalue, answer, false);
                }
                else
                {
                    action(jvalue, answer, true);
                }
            }
            catch (http_exception const & e)
            {
                wcout << "HTTP exception in handle_request: " << e.what() << endl;
            }
        })
        .wait();

    request.reply(status_codes::OK, answer);
}

void handle_post(http_request request)
{
    TRACE("\nHandle POST\n");

    handle_request(
        request, 
        [](const json::value & jvalue, json::value & answer, bool bNull)
        {

            const utility::string_t sID("id");
            const utility::string_t sText("text");
            const utility::string_t sState("state");


            if( bNull )
            {
                wcout << "jvalue must be null, setting some default values..." << endl;
                json::value group;              
                group[sID] = json::value::string("1");
                group[sText] = json::value::string("Hello");
                group[sState] = json::value::string("closed");
                answer[0] = group;
            }
            else
            {
                // To be written once the null case is sorted
            }
        }
    );
}

int main()
{
    uri_builder uri("http://w.x.y.z:1024/testrest");
    http_listener listener(uri.to_uri());

    listener.support(methods::POST, handle_post);
    try
    {
        listener
            .open()
            .then([&listener]()
                {
                    TRACE(L"\nStarting to listen\n");
                })
            .wait();

        while (true);
    }
    catch (exception const & e)
    {
        wcout << e.what() << endl;
    }

    return 0;
}

这个编译得很干净,我可以使用以下命令在linux服务器上启动服务:

./testrest &
Starting to listen

为了帮助调试,我一直在同一个Linux服务器上使用curl作为POST客户端。我一直在使用以下命令发送一个内容长度为0的POST请求:

curl -i -X POST -H 'Content-Type: application/json' http://w.x.y.z:1024/testrest

curl的输出如下:

HTTP/1.1 200 OK
Content-Length: 44
Content-Type: application/json

[{"id":"1","state":"closed","text":"Hello"}]

来自我服务的控制台消息是这样的:

Handle POST

Handle_request
POST /testrest HTTP/1.1
Accept: */*
Content-Type: application/json
Host: w.x.y.z:1024
User-Agent: curl/7.29.0


jvalue must be null, setting some default values...

前两行对应于代码中的TRACE次调用。中间部分由这部分代码生成:

// Spit out the HTTP header to the console...
const auto HeaderString = request.to_string();
wcout << HeaderString.c_str() << endl;

基于curl输出,这是一个字典对象数组,只有一个条目长,我希望这个服务应该可以正常使用客户端上的jeasyui javascript。但事实并非如此。我的异步树从不填充,我根本看不到任何东西。

我怀疑编码有问题,因此我使用web2py编写了另一个服务来测试它是否可以在那里工作。我的default.py控制器中存在以下代码:

@service.json
def testweb2py():

    aRet=[]
    if request.post_vars.id is None:
        mydict={'id':'1','text':'Hello','state':'closed'}
        aRet.append(mydict)
    return aRet

将我的客户端easyui-tree HTML修改为指向web2py网址后,它会完美填充,我可以看到该节点。我用curl点击了web2py service.json代码,看看输出可能有什么不同:

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 18:17:17 GMT
Server: Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
X-Powered-By: web2py
Expires: Mon, 23 Jan 2017 18:17:18 GMT
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Length: 99
Content-Type: application/json; charset=utf-8

[{"text": "Hello", "state": "closed", "id": "1"}]

除了内容标题完全不同之外,还有一行我怀疑它可能与它有关:

Content-Type: application/json; charset=utf-8

在对cpprest服务的调用中,curl的头输出中不包含charset=utf-8。如果我使用-o开关将curl输出转储到文件,我看不到编码之间有任何明显的区别。我在json的格式中看到的唯一不同的是一些额外的空格和顺序:

[{"text": "Hello", "state": "closed", "id": "1"}]    // web2py version
[{"id":"1","state":"closed","text":"Hello"}]         // cpprest version

我无法控制json字典的发送顺序,但我怀疑它与它有什么关系。为值条目添加前缀的额外空格似乎也无关紧要。

我已经在microsoft.github.io/cpprestsdk/index.html上搜索了cpprest文档, 我找不到任何与设置输出编码有关的内容。 http_request::reply有许多覆盖,其中包括设置内容类型的选项,并且我已经使用硬编码字符串为json正文和内容类型调用它们。 json/application; charset=utf-8,一切都无济于事。我不知道这些覆盖如何与json :: value对象一起使用,所以我不认为这是cpprest库的最佳路径或可行用途。

jeasyui javascript代码似乎是故意混淆的,我几乎没有信心能够通过POST调用找出它正在做什么。也许熟悉jeasyui的人可以指出调试异步POST的可行方法吗?

请帮忙!

1 个答案:

答案 0 :(得分:1)

所以我弄清楚发生了什么。在Chrome中打开了开发人员工具控制台,发现了以下错误消息:

XMLHttpRequest无法加载http://w.x.y.z:1024/testrest。 No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; http://w.x.y.z&#39;因此不允许访问。

因此它与我的json数据的格式或编码无关,而是json服务被识别为与生成客户端HTML的Web服务器不同的资源,这是事实,因此Chrome阻止了它。为了解决这个问题,我不得不在我发送回客户端的响应中添加一些头字段,并添加一个支持方法来处理来自任何可能需要它们的客户端的OPTIONS查询。

在我的main()函数中,我添加了:

listener.support(methods::OPTIONS, handle_options);

然后我写了相应的函数:

void handle_options(http_request request)
{
    http_response response(status_codes::OK);   
    response.headers().add(U("Allow"), U("POST, OPTIONS"));

    // Modify "Access-Control-Allow-Origin" header below to suit your security needs.  * indicates allow all clients
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);
}

最后,我必须在handle_request中向request.reply添加相同的标题:

http_response response(status_codes::OK);

// Without these headers, the client browser will likely refuse the data and eat it
response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
response.set_body(answer);
request.reply(response);    

还有其他问题......最突出的是jeasyui类easyui_tree不会使用内容类型application/json POST数据。相反,它发布了一个application/x-www-form-urlencoded的Content-Type,所以我不得不添加一个函数来使用libcurl解析url编码。这也意味着用request.extract_json()替换request.extract_string()以及对cpprest使用的相应lambda函数的相关修改。

这是最终的示例代码,也许对在这些领域工作的其他人有用。它是用cpprest(在linux上,不少)编写json服务的一个功能齐全的例子,它响应来自easyui_tree的异步POST请求。依赖关系:boost,cpprest和libcurl-devel。

#include <boost/algorithm/string/replace.hpp>
#include <cpprest/http_listener.h>
#include <cpprest/json.h>
#include <curl/curl.h>
#pragma comment(lib, "cpprestlib" )

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;

#include <iostream>
#include <map>
#include <vector>
#include <set>
#include <string>
using namespace std;

#define TRACE(msg)            wcout << msg 

void build_json( const utility::string_t &source, json::value &jvalue )
{
    // Use libcurl to unescape the POST body for us
    vector<string> splitvec;

    // We don't own the string created by curl_easy_unescape, so add a custom deleter
    string text = shared_ptr<char>( curl_easy_unescape( 0, source.c_str(), 0, 0 ), curl_free).get();

    // This works for this specific example of jeasyui, the class 'easyui-tree', which only passes id=... in the POST.  
    // Need custom handler to deal with more complicated data formats   
    boost::split( splitvec, text, boost::is_any_of("="));       
    if( splitvec.size() == 2 )
    {
        jvalue[splitvec.at(0)] = json::value::string(splitvec.at(1));
    }
}

void handle_request(http_request request, function<void(const json::value &, json::value &, bool)> action)
{
    json::value answer;

    auto objHeader = request.headers();
    auto sContentType = objHeader["Content-Type"];

    // Two cases: 
    // 1) The very first call from easyui_tree, when the HTML is first loaded, will make a zero-length POST with no 'Content-Type' in the header
    // 2) Subsequent calls from easyui_tree (e.g. when user opens a node) will have a Content-Type of 'application/x-www-form-urlencoded'
    // Nowhere does easyui_tree send json data in the POST, although it expects json in the reply
    if( sContentType.size() == 0 || 
        !strncasecmp( sContentType.c_str(), "application/x-www-form-urlencoded", strlen("application/x-www-form-urlencoded") ) )
    {
        request
            .extract_string()
            .then([&answer, &action](pplx::task<utility::string_t> task) {
                try
                {
                    const auto & svalue = task.get();
                    json::value jvalue;
                    if ( svalue.size() == 0 )
                    {
                        action(jvalue, answer, true);
                    }
                    else
                    {                       
                        build_json( svalue, jvalue );                       
                        action(jvalue, answer, false);
                    }
                }
                catch (http_exception const & e)
                {
                    wcout << "HTTP exception in handle_request: " << e.what() << endl;
                }
            })
            .wait();
    }
    else
    {
        // This Content-Type doesn't appear with easyui_tree, but perhaps it's still useful for future cases...
        if( !strncasecmp( sContentType.c_str(), "application/json", strlen("application/json") ) )
        {
            request
                .extract_json()
                .then([&answer, &action](pplx::task<json::value> task) {
                    try
                    {
                        const auto & jvalue = task.get();
                        if (!jvalue.is_null())
                        {
                            action(jvalue, answer, false);
                        }
                        else
                        {
                            action(jvalue, answer, true);
                        }
                    }
                    catch (http_exception const & e)
                    {
                        wcout << "HTTP exception in handle_request: " << e.what() << endl;
                    }
                })
                .wait();
        }
    }
    http_response response(status_codes::OK);

    // Without these headers, the client browser will likely refuse the data and eat it
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    response.set_body(answer);
    request.reply(response);    
}

void handle_options(http_request request)
{
    http_response response(status_codes::OK);   
    response.headers().add(U("Allow"), U("POST, OPTIONS"));

    // Modify "Access-Control-Allow-Origin" header below to suit your security needs.  * indicates allow all clients
    response.headers().add(U("Access-Control-Allow-Origin"), U("*"));
    response.headers().add(U("Access-Control-Allow-Methods"), U("POST, OPTIONS"));
    response.headers().add(U("Access-Control-Allow-Headers"), U("Content-Type"));
    request.reply(response);
}

void handle_post(http_request request)
{
    handle_request(
        request, 
        [](const json::value & jvalue, json::value & answer, bool bInitialize)
        {
            if( bInitialize )
            {
                // First time the tree is being loaded, first id will be 16, which will yield us 16 child nodes when it POSTs back
                json::value jreply;       
                jreply[U("id")] = json::value::string("16");
                jreply[U("text")] = json::value::string("Parent");
                jreply[U("state")] = json::value::string("closed");
                answer[0] = jreply;
            }
            else
            {
                // User has opened a node
                if( jvalue.type() == json::value::value_type::Object )
                {
                    if( jvalue.has_field( "id" ) )
                    {
                        auto & key = jvalue.at( "id" );
                        if( key.is_string() )
                        {
                            auto value = key.as_string();
                            int id = atoi(value.c_str());
                            stringstream ss;
                            ss << (id / 2);  // Each successive layer has half as many child nodes as the one prior
                            for( int i = 0; i < id; i++ )
                            {
                                json::value jreply;
                                jreply[U("id")] = json::value::string(ss.str());
                                jreply[U("text")] = json::value::string("Child");
                                jreply[U("state")] = json::value::string("closed");
                                answer[i] = jreply;
                            }
                        }
                    }
                }               
            }
        }
    );
}

int main()
{
    uri_builder uri("http://yourserver.com:1024/testrest");
    http_listener listener(uri.to_uri());

    listener.support(methods::POST, handle_post);
    listener.support(methods::OPTIONS, handle_options);
    try
    {
        listener
            .open()
            .then([&listener]()
                {
                    TRACE(L"\nStarting to listen\n");
                })
            .wait();

        while (true);
    }
    catch (exception const & e)
    {
        wcout << e.what() << endl;
    }
    return 0;
}

当然还有相应的HTML,假设标题中引用了所有jeasyui脚本:

<ul id="tt" method="POST" class="easyui-tree" url="http://yourserver.com:1024/testrest">
</ul>