c++ 调用restful API 示例
时间: 2024-11-11 18:14:57 浏览: 12
C++实现 Https Server 支持 restful json
在C++中直接调用RESTful API通常不是直接操作,因为C++本身并不支持HTTP请求。但是,你可以通过一些库如cpr (C++ REST Client) 或 Poco C++ Libraries 来处理这样的任务。这里是一个基本的例子:
```cpp
#include "poco/http_client.h"
#include "poco/http_client_request.h"
#include "poco/http_response.h"
using namespace Poco;
void callRESTAPI(const std::string& apiUrl, const std::string& method, const std::string& requestBody = "")
{
try {
HTTPClientSession session("example.com", 80);
HTTPRequest request(Poco::HTTPRequest::HTTP_METHOD_GET, apiUrl, HTTPMessage::HTTP_1_1);
if (method == "POST") {
request.setMethod(HTTPRequest::HTTP_POST);
request.setRequestBody(requestBody);
}
HTTPResponse response;
session.sendRequest(request, response);
// 检查响应状态码
if (response.getStatus() == HTTPResponse::HTTP_OK) {
std::cout << "Response body:\n" << response.stream().str();
} else {
std::cerr << "Error calling API: " << response.statusText() << ", status code: " << response.getStatus() << std::endl;
}
} catch (Exception& e) {
std::cerr << "Error: " << e.displayText() << std::endl;
}
}
int main()
{
callRESTAPI("/api/resource", "GET");
callRESTAPI("/api/resource", "POST", "{\"key\":\"value\"}");
return 0;
}
```
在这个示例中,我们创建了一个`callRESTAPI`函数,它接受API URL、HTTP方法(GET或POST)以及可选的POST请求体。然后使用Poco库发送HTTP请求并处理响应。
阅读全文