52 lines
1.3 KiB
C++
52 lines
1.3 KiB
C++
#include "network/http_handler.h"
|
|
#include "esp_http_client.h"
|
|
#include "esp_log.h"
|
|
#include "string.h"
|
|
|
|
HttpHandler::HttpHandler(const esp_http_client_config_t&& config, WifiHandler* wifiHandler)
|
|
: wifiHandler(wifiHandler) {
|
|
this->client = esp_http_client_init(&config);
|
|
}
|
|
|
|
HttpHandler::~HttpHandler() {
|
|
if (this->client) {
|
|
esp_http_client_cleanup(this->client);
|
|
}
|
|
}
|
|
|
|
esp_err_t HttpHandler::set_method(esp_http_client_method_t method) {
|
|
return esp_http_client_set_method(this->client, method);
|
|
}
|
|
|
|
esp_err_t HttpHandler::set_header(const char* header, const char* value) {
|
|
return esp_http_client_set_header(this->client, header, value);
|
|
}
|
|
|
|
esp_err_t HttpHandler::set_post_field(const char* field, size_t len) {
|
|
return esp_http_client_set_post_field(this->client, field, len);
|
|
}
|
|
|
|
esp_err_t HttpHandler::perform_request() {
|
|
return esp_http_client_perform(this->client);
|
|
}
|
|
|
|
void HttpHandler::get_body(
|
|
char*& buffer,
|
|
int& total_len
|
|
) {
|
|
total_len = esp_http_client_get_content_length(this->client);
|
|
buffer = new char[total_len + 1]; // +1 for null-terminator
|
|
if (buffer) {
|
|
int read_len = esp_http_client_read(this->client, buffer, total_len);
|
|
if (read_len >= 0) {
|
|
buffer[read_len] = '\0'; // null-terminate
|
|
} else {
|
|
delete[] buffer;
|
|
buffer = nullptr;
|
|
total_len = 0;
|
|
}
|
|
} else {
|
|
total_len = 0;
|
|
}
|
|
}
|