Last active
April 17, 2024 11:04
-
-
Save sunmeat/6f82042db47e60081ffb2afef1c56ebd to your computer and use it in GitHub Desktop.
cpp console app and php integration (http example) curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <curl/curl.h> | |
#include <string> | |
using namespace std; | |
/* | |
1) заходим на https://github.com/microsoft/vcpkg | |
2) качаем архив (code > download) | |
3) распаковываем архив, переносим файлы в C:\vcpkg | |
4) запускаем bootstrap-vcpkg.bat, в папке сформируется vcpkg.exe | |
5) запускаем cmd.exe, набираем команду C:\vcpkg\vcpkg install curl | |
6) ждём до конца (минут 5), набираем команду C:\vcpkg\vcpkg integrate install | |
7) параметры виндовс > изменение системных переменных среды > системные переменные > Path > Изменить | |
8) добавить туда строку C:\vcpkg\installed\x64-windows\bin, поставить её после %system root% | |
*/ | |
class CurlHandler { | |
public: | |
CurlHandler() { | |
// инициализация библиотеки cURL | |
curl_global_init(CURL_GLOBAL_DEFAULT); | |
// создание объекта CURL | |
curl = curl_easy_init(); | |
if (!curl) { | |
cout << "Возникли проблемы с инициализацией объекта CURL.\n"; | |
} | |
} | |
~CurlHandler() { | |
// освобождение ресурсов объекта CURL | |
if (curl) { | |
curl_easy_cleanup(curl); | |
} | |
// oсвобождение библиотеки cURL | |
curl_global_cleanup(); | |
} | |
// метод для выполнения HTTP POST-запроса | |
CURLcode performPostRequest(const string& postData) { | |
if (curl) { | |
// установка URL | |
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); | |
// установка данных для POST-запроса | |
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postData.c_str()); | |
// установка функции обратного вызова для обработки данных | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlHandler::WriteCallback); | |
// установка указателя на объект string для хранения данных | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseData); | |
// Выполнение запроса | |
return curl_easy_perform(curl); | |
} | |
return CURLE_FAILED_INIT; | |
} | |
// геттер для URL | |
string getUrl() const { | |
return url; | |
} | |
// сеттер для URL | |
void setUrl(const string& newUrl) { | |
url = newUrl; | |
} | |
// геттер для данных ответа | |
string getResponseData() const { | |
return responseData; | |
} | |
private: | |
CURL* curl; | |
string url; | |
string responseData; | |
// метод обратного вызова для обработки данных | |
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, string* output) { | |
size_t total_size = size * nmemb; | |
output->append(static_cast<char*>(contents), total_size); | |
return total_size; | |
} | |
}; | |
class ConsoleIO { | |
public: | |
// метод для ввода значения с клавиатуры | |
static int getInputInt(const string& prompt) { | |
int value; | |
cout << prompt; | |
cin >> value; | |
return value; | |
} | |
// метод для вывода сообщения в консоль | |
static void displayMessage(const string& message) { | |
cout << message << "\n"; | |
} | |
}; | |
class PHPRequestDemo { | |
public: | |
static void SumTwoNumbers() { | |
CurlHandler handler; | |
// установка URL | |
handler.setUrl("http://sunmeat.atwebpages.com/volley/script.php"); | |
// ввод значений с клавиатуры | |
int first = ConsoleIO::getInputInt("Введите первое значение: "); | |
int second = ConsoleIO::getInputInt("Введите второе значение: "); | |
// формирование строки данных для POST-запроса | |
string postData = "first=" + to_string(first) + "&second=" + to_string(second); | |
if (handler.performPostRequest(postData) == CURLE_OK) { | |
ConsoleIO::displayMessage("Ответ сервера: " + handler.getResponseData()); | |
} | |
else { | |
ConsoleIO::displayMessage("Запрос завершился неудачей."); | |
} | |
} | |
static void InsertSQLRow(const string& name) { | |
CurlHandler handler; | |
handler.setUrl("http://sunmeat.atwebpages.com/volley/upload.php"); // Замените на свой адрес скрипта вставки | |
string postData = "name=" + name; | |
if (handler.performPostRequest(postData) == CURLE_OK) { | |
ConsoleIO::displayMessage("Строка успешно добавлена в базу данных."); | |
} | |
else { | |
ConsoleIO::displayMessage("Не удалось выполнить запрос на добавление строки."); | |
} | |
} | |
}; | |
int main() { | |
setlocale(0, ""); | |
PHPRequestDemo::SumTwoNumbers(); | |
PHPRequestDemo::InsertSQLRow("Odessa-KND-221"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment