CMakeLists.txt添加网络请求库 REQUIRES esp_http_client
效果图
D (14235) HTTP_CLIENT: content_length = -1 需要直接拼接content_length才能打印
#include <stdio.h>
#include <string.h>
#include "esp_log.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#include "esp_http_client.h"static const char *TAG = "HTTP_CLIENT";#define MAX_HTTP_OUTPUT_BUFFER 2048static char local_response_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};// HTTP 回调处理函数
esp_err_t _http_event_handler(esp_http_client_event_t *evt) {switch (evt->event_id) {case HTTP_EVENT_ON_DATA:// 直接拼接数据(无论是否 chunked)if (evt->data_len > 0 && evt->data != NULL) {strncat(local_response_buffer, (char *)evt->data, evt->data_len);// size_t len = strlen(local_response_buffer);// size_t copy_len = MIN(evt->data_len, MAX_HTTP_OUTPUT_BUFFER - len - 1);// strncat(local_response_buffer, (char *)evt->data, copy_len);}break;default:break;}return ESP_OK;
}void http_get_and_parse_json(char *url) {// 初始化NVSesp_err_t ret = nvs_flash_init();if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {ESP_ERROR_CHECK(nvs_flash_erase());ret = nvs_flash_init();}ESP_ERROR_CHECK(ret);// 连接WIFI(使用 examples 中的 common 配置)//如果你没有连接wifi,需要实现连接wifi的代码// ESP_ERROR_CHECK(esp_netif_init());// ESP_ERROR_CHECK(esp_event_loop_create_default());// ESP_ERROR_CHECK(example_connect()); // 自动连接WiFi的代码这里省略// 配置HTTP客户端esp_http_client_config_t config = {.url = url, // 你要访问的网页URL.event_handler = _http_event_handler,.user_data = local_response_buffer, // 将缓冲区传入回调};esp_http_client_handle_t client = esp_http_client_init(&config);esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK) {// ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %d",// esp_http_client_get_status_code(client),// esp_http_client_get_content_length(client));ESP_LOGI(TAG, "Response:\n%s", local_response_buffer);} else {ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err));}esp_http_client_cleanup(client);
}
头文件.h
#ifndef HTTP_JSON_CLIENT_H
#define HTTP_JSON_CLIENT_H#ifdef __cplusplus
extern "C" {
#endif/*** @brief 使用 HTTP GET 请求指定 URL 并解析返回的 JSON 数据* * @param url 目标请求地址,如 "http://yourserver.com/api/data"*/
void http_get_and_parse_json(const char *url);#ifdef __cplusplus
}
#endif#endif // HTTP_JSON_CLIENT_H
测试php
<?php
$data = ['status' => 'ok','message' => '你好 ESP32!'
];$json = json_encode($data, JSON_UNESCAPED_UNICODE);
header('Content-Type: application/json');
header('Content-Length: ' . strlen($json));
header('Connection: close'); // 防止 keep-alive 导致 chunked
echo $json;