【问题标题】:C++ Networking: Request method POSTC++ 网络:请求方法 POST
【发布时间】:2021-01-03 19:35:09
【问题描述】:

我正在尝试与某个服务器通信。要获取用户名(有权限),我需要做一些类似注册的事情:HTTP 请求方法 POST 发送包含 {“devicetype”:“devicename”} 的类似 json 的正文。 O 试图用 ASIO 库来做。

asio::error_code ec;
asio::io_context context;
asio::ip::tcp::endpoint endpoint(asio::ip::make_address("ipAddress", ec), 80);
asio::ip::tcp::socket socket(context);
if (!ec)
    {
        std::cout << "Succesfully connected\n";
    }
    else
    {
        std::cout << "Failed to connect to address: \n" << ec.message() << std::endl;
    }
if (socket.is_open())
    {
std::string sRequest =
            "POST /api HTTP/1.1\r\n"
            "Host: ipAddress \r\n"
            "Body: {\"devicetype\": \"devicename\"}"
            "Connection: close\r\n\r\n";
socket.write_some(asio::buffer(sRequest.data(), sRequest.size()), ec);

/*Reading received message and getting error message from server*/
}

错误提示:“正文中的参数无效/缺失”。参数正确。问题可能与我发送的消息格式(sRequest)有关。如何指定 json 正文来发送消息?

感谢您的帮助。

【问题讨论】:

    标签: c++ http networking request


    【解决方案1】:

    您显示的不是格式正确的 HTTP 请求。 HTTP 中没有 Body 标头。 JSON 数据需要在终止标头的\r\n\r\n 之后。并且您需要添加 Content-Type 和 Content-Length 标头,以便服务器知道您要发布什么样的数据以及它有多大。

    试试这个:

    std::string json = "{\"devicetype\": \"devicename\"}";
    std::string sRequest =
                "POST /api HTTP/1.1\r\n"
                "Host: ipAddress\r\n"
                "Content-Type: application/json\r\n"
                "Content-Length: " + std::to_string(json.size()) + "\r\n"
                "Connection: close\r\n\r\n" + json;
    

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多