c++ - CPPRest SDK 向服务器发出 HTTP 请求

标签 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 测试过的服务器,所以我很确定我的代码出了问题。请帮忙,谢谢

最佳答案

含糊不清。 如果您说请求未到达服务器,则执行此代码时监听器可能有问题。

你的请求格式正确,正在运行,你可以尝试将body(u_id, pwd)包成json,看看是否可行。

底线是调试或共享您的服务器代码可能有助于进一步澄清事情。

关于c++ - CPPRest SDK 向服务器发出 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030532/

相关文章:

c++ - basic_streambuf::seekoff 当 ios_base::in | 应该返回什么? ios_base::out 被指定了吗?

json - 将 JSON 从 Express 发送到外部服务器

json - 在 json 中没有嵌套数组的情况下哈希到 json

c++ - 在计算着色器中计算帧缓冲区的颜色直方图

c++ - 为什么 C++ 复制构造函数必须使用 const 对象?

c++ - 我如何摆脱这些警告?

java - 根据对象属性动态定义XML标签

rest - 通过 REST API 列出 VSTS 工作项列表

java - 我正在尝试使用 React 来使用 RESTful API

ios - 带有网络管理面板的移动应用程序