#include "net_http.h" #include "esp_log.h" #include "esp_http_client.h" #include "miscellaneous_interface.h" #define MAX_HTTP_OUTPUT_BUFFER 1024 EXT_RAM_BSS_ATTR static char http_data[MAX_HTTP_OUTPUT_BUFFER] = {0}; //! 需要定义为全局静态变量,否则会导致任务的堆栈溢出 #define HTTP_HEADER_CONTENT_TYPE "application/json" static const char *TAG = "HTTP_CLIENT"; QueueHandle_t res_queue; esp_err_t _http_event_handler(esp_http_client_event_t *evt) { // 缓存http响应的buffer static char *output_buffer; // 已经读取的字节数 static int output_len; switch (evt->event_id) { case HTTP_EVENT_ERROR: ESP_LOGD(TAG, "HTTP_EVENT_ERROR"); break; case HTTP_EVENT_ON_DATA: // 如果配置了user_data buffer,则把响应复制到该buffer中 memcpy(http_data + output_len, evt->data, evt->data_len); output_len += evt->data_len; break; case HTTP_EVENT_ON_FINISH: ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); if (output_buffer != NULL) { free(output_buffer); output_buffer = NULL; } output_len = 0; break; case HTTP_EVENT_DISCONNECTED: ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED"); if (output_buffer != NULL) { free(output_buffer); output_buffer = NULL; } output_len = 0; break; default: break; } return ESP_OK; } void net_http_get(net_http_config_t p_config) { esp_http_client_config_t config = { .url = p_config.url, .timeout_ms = 5000 * 2 * 2, .user_data = (void *) http_data, .disable_auto_redirect = true, .method = HTTP_METHOD_GET, .event_handler = _http_event_handler}; memset(http_data, 0, MAX_HTTP_OUTPUT_BUFFER); //清空http缓存区 esp_http_client_handle_t client = esp_http_client_init(&config); esp_http_client_set_header(client, "Content-Type", HTTP_HEADER_CONTENT_TYPE); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { if (p_config.callback != NULL) { p_config.callback(http_data, p_config.user_data); } } else { if (p_config.callback != NULL) { p_config.callback(NULL, p_config.user_data); } } esp_http_client_close(client); esp_http_client_cleanup(client); } void net_http_post(const char *post_data, net_http_config_t p_config) { esp_http_client_config_t config = { .url = p_config.url, .timeout_ms = 5000 * 2 * 2, .user_data = (void *) http_data, .event_handler = _http_event_handler}; memset(http_data, 0, MAX_HTTP_OUTPUT_BUFFER); //清空http缓存区 esp_http_client_handle_t client = esp_http_client_init(&config); esp_http_client_set_method(client, HTTP_METHOD_POST); esp_http_client_set_header(client, "Content-Type", HTTP_HEADER_CONTENT_TYPE); ESP_ERROR_CHECK(esp_http_client_set_post_field(client, post_data, strlen(post_data))); esp_err_t err = esp_http_client_perform(client); if (err == ESP_OK) { if (p_config.callback != NULL) { p_config.callback(http_data, p_config.user_data); } } else { if (p_config.callback != NULL) { p_config.callback(NULL, p_config.user_data); } } esp_http_client_close(client); esp_http_client_cleanup(client); }