diff --git a/src/HTTP.cpp b/src/HTTP.cpp index a3898ea..e416731 100644 --- a/src/HTTP.cpp +++ b/src/HTTP.cpp @@ -96,53 +96,55 @@ namespace ESPAdmin }; esp_http_client_handle_t client = esp_http_client_init(&config); + if (client == nullptr) + { + _logger.error("failed to init http client"); + return ""; + } esp_http_client_set_header(client, "Api-Key", Store::options.apiKey); - esp_http_client_set_header(client, "Content-Type", contentType.c_str()); esp_err_t err = esp_http_client_open(client, content.length()); - - if (err == ESP_OK) + if (err != ESP_OK) { - int wlen = esp_http_client_write(client, content.c_str(), content.length()); - - if (wlen == -1) - { - _logger.error("failed to write"); - } - else - { - int contentLength = esp_http_client_fetch_headers(client); - - if (contentLength == -1) - { - _logger.error("failed to read"); - } - else - { - int statusCode = esp_http_client_get_status_code(client); - - if (statusCode < 200 || statusCode >= 300) - { - _logger.error("failed with %d", statusCode); - } - else - { - esp_http_client_read_response(client, response, Store::options.httpMaxResponseSize); - } - } - } + _logger.error("failed to open connection"); + esp_http_client_cleanup(client); + return ""; + } + int wlen = esp_http_client_write(client, content.c_str(), content.length()); + if (wlen == -1) + { + _logger.error("failed to write"); esp_http_client_close(client); + esp_http_client_cleanup(client); + return ""; + } + int contentLength = esp_http_client_fetch_headers(client); + if (contentLength == -1) + { + _logger.error("failed to read"); + esp_http_client_close(client); esp_http_client_cleanup(client); + return ""; } - else + + int statusCode = esp_http_client_get_status_code(client); + if (statusCode < 200 || statusCode >= 300) { - _logger.error("failed to open connection"); + _logger.error("failed with %d", statusCode); + esp_http_client_close(client); + esp_http_client_cleanup(client); + return ""; } + esp_http_client_read_response(client, response, Store::options.httpMaxResponseSize); + + esp_http_client_close(client); + esp_http_client_cleanup(client); + return String(response); } }