53 lines
1.6 KiB
C++
53 lines
1.6 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
#include <curl/curl.h>
|
|
|
|
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
|
|
((std::string*)userp)->append((char*)contents, size * nmemb);
|
|
return size * nmemb;
|
|
}
|
|
|
|
std::string httpRequest(const std::string& url,
|
|
const std::string& method,
|
|
const std::string& body = "") {
|
|
CURL* curl;
|
|
CURLcode res;
|
|
std::string readBuffer;
|
|
|
|
curl = curl_easy_init();
|
|
if (curl) {
|
|
struct curl_slist* headers = NULL;
|
|
headers = curl_slist_append(headers, "Content-Type: application/json");
|
|
|
|
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
|
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method.c_str());
|
|
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
|
|
|
|
if (!body.empty()) {
|
|
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
|
|
}
|
|
|
|
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
|
|
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
|
|
|
|
res = curl_easy_perform(curl);
|
|
curl_easy_cleanup(curl);
|
|
}
|
|
return readBuffer;
|
|
}
|
|
|
|
int main() {
|
|
std::string base = "http://localhost:8080/shop-1.0-SNAPSHOT/api/items";
|
|
|
|
// GET all items
|
|
std::cout << "GET all items:\n" << httpRequest(base, "GET") << "\n\n";
|
|
|
|
// GET item by ID
|
|
std::cout << "GET item 1:\n" << httpRequest(base + "/1", "GET") << "\n\n";
|
|
|
|
// POST new item
|
|
std::string newItem = R"({"name":"Mouse","price":1.25, "description":"Logitek gaming mouse"})";
|
|
std::cout << "POST new item:\n" << httpRequest(base, "POST", newItem) << "\n\n";
|
|
return 0;
|
|
}
|