You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用Casablanca调用REST API并POST XML的实现方法问询

Solution for XML Request Body in cpprestsdk

Got it, let's get this sorted out! The problem with your current code is that you're generating JSON content but passing it off as XML to the API—we need to construct proper XML instead of repurposing JSON. Here's how to adjust your code:

Modified Code

return pplx::create_task([] { 
    // Construct the XML request body to match your API's expected schema
    std::wstring xmlData = L"<Person>"
                           L"<name>Joe Smith</name>"
                           L"<hobby>Baseball</hobby>"
                           L"</Person>";

    http_client client(L"http://localhost:5540/api/values"); 
    // Pass the valid XML string, with correct Content-Type header
    return client.request(methods::POST, L"", xmlData.c_str(), L"application/xml"); 
}).then([](http_response response) { 
    if (response.status_code() == status_codes::OK) { 
        auto body = response.extract_string(); 
        std::wcout << L"Added new Id: " << body.get().c_str() << std::endl; 
        return std::stoi(body.get().c_str()); 
    } 
    return 0; 
});

Key Changes Explained

  • Replaced JSON generation with XML construction: Instead of using json::value, we build a raw XML string that matches the exact structure your API expects. Double-check that element names (like <Person>, <name>) align with the API's documentation.
  • Fixed request body format: We pass the XML string directly to client.request() instead of converting JSON to a string, which ensures the API receives valid XML content.
  • Preserved existing response logic: The .then() block for processing the API response stays unchanged, since it doesn't depend on how the request was formatted.

Important Note

If your data includes special characters like <, >, &, ", or ', you'll need to escape them properly to avoid invalid XML. For example, replace & with &amp;, < with &lt;, etc. For more complex XML structures, consider using an XML library (like tinyxml2 or pugixml) to build the document safely instead of manual string concatenation.

内容的提问来源于stack exchange,提问作者Frein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:59