CPPRest SDK向服务器发出HTTP请求

时间:2016-08-19 03:10:44

标签: c++ json rest casablanca

在CPPRest SDK(2.8)测试期间,我初始化了一个模拟用户登录到本地服务器的HTTP请求,我希望返回一个JSON字符串,指示登录是否成功。这是我写的代码。

void printJSON(json::value v)
{
if (!v.is_null()){
    // Loop over each element in the object
    for (auto iter = v.as_object().cbegin(); iter != v.as_object().cend(); ++iter){
        const string &key = iter->first;
        const json::value &value = iter->second;

        if (value.is_object() || value.is_array()){
            if(key.size() != 0){
                std::wcout << "Parent: " << key.c_str() << std::endl;
            }
            printJSON(value);
            if(key.size() != 0){
                std::wcout << "End of Parent: " << key.c_str() << std::endl;
            }
        }else{
            std::wcout << "Key: " << key.c_str() << ", Value: " << value.to_string().c_str() << std::endl;
        }
    }
}
}

void login(){
http_client client("http://localhost:8080/user");

http_request request(methods::POST);
request.headers().add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.headers().add("Content-Length", "100");
request.headers().add("Host", "testhost.com");
request.headers().add("X-Requested-With", "XMLHttpRequest");
request.set_body("u_id=test_admin&pwd=123456789");

pplx::task<void> task = client.request(request)
        .then([](http_response response)-> pplx::task<json::value>{
            if(response.status_code() == status_codes::OK){
                return response.extract_json();
            } else {
                return pplx::task_from_result(json::value());
            };})
        .then([](pplx::task<json::value> previousTask){
            try{
                const json::value & v = previousTask.get();
                printJSON(v);
            } catch(const http_exception &e){
                std::cout<<e.what()<<std::endl;
            }
        });
try{
    task.wait();
} catch(std::exception &e){
    std::cout<<e.what()<<std::endl;
}
}

当我运行此代码时,没有任何反应,似乎请求永远不会到达使用JSP测试过的服务器,所以我很确定我的代码出了问题。请帮助,谢谢

1 个答案:

答案 0 :(得分:1)

模糊。 如果您说请求未到达服务器,则在您执行此代码时,侦听器可能存在问题。

您的请求格式正确且正在运行,您可以尝试将正文(u_id,pwd)包装到json中,看看它是否有效。

底线是调试或共享您的服务器代码可能有助于澄清更多内容。