如何使用 C++ 中的 cpprestsdk 发布 json 数据并从本地服务器获取响应

how to POST json data and get responses from the local server by using cpprestsdk in c++

本文关键字:服务器 响应 获取 数据 C++ 何使用 中的 cpprestsdk json 发布      更新时间:2023-10-16

谢谢你回答我的问题。

关于使用 cpprestsdk 的 c++ 中的 POST 请求。

我想将 json 数据发送到本地服务器,并使用 c++ 中的 cpprestsdk 通过 POST 从中获得响应。我做了一个程序,但它不起作用。我只能发送数据,但无法获取响应数据。 字符串 fomrat OK! 我可以相互转换字符串和 JSON 对象。

请帮助我。 我想这样做。

[伪源代码,如 C# 或 Java]

string POST(string postData){;
string receive = sendtoServer("http://localhost:8080/",postData);
return receive;
}

[Linux 或 window 命令 cURL]

curl -X POST http://localhost:8080/ -d '{"age":20,"sex":male"}'
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <cpprest/http_client.h>
using namespace web;  
using namespace web::http;  
using namespace web::http::client;  
auto POST(json::value postData){  
http_client client(L"http://localhost:8080/");  
auto receive = client.request(methods::POST, L"", postData.serialize(),   
L"application/json").get().to_string().c_str();  
printf("[DEBUG] receive = ");  
std::wprintf(receive);  
return  receive;  
}  

建立成功,但它不起作用。 我不太了解并发::任务<>所以告诉我我的错误。 谢谢。enter code here

试试

http_client客户端(L("http://localhost:8080/"((;
自动接收 = client.request(methods::P OST, L("(, postData.serialize((,
L("application/json"((.get((.to_string((.c_str((;

而不是

http_client客户端(L"http://localhost:8080/"(;
自动接收 = client.request(methods::P OST, L", postData.serialize((,
L"application/json"(.get((.to_string((.c_str((;

请注意在"L"之后使用括号。