在一些物聯網應用場景中,我們需要從服務器或者其它設備中獲取來自網絡的JSON包來實現數據的傳輸和控制。下面是一些ESP32獲取JSON包的常見方式。
使用Arduino IDE
#include <WiFi.h> #include <HTTPClient.h> void setup() { Serial.begin(115200); WiFi.begin("your_SSID", "your_PASSWORD"); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); } String url = "http://your_api_url"; // 注意URL需要http或https前綴 HTTPClient http; http.begin(url); int httpCode = http.GET(); if (httpCode >0) { String payload = http.getString(); Serial.println(payload); } http.end(); } void loop() { }
使用ESP-IDF
#include "esp_http_client.h" void http_event_handler(esp_http_client_event_t *evt) { switch(evt->event_id) { case HTTP_EVENT_ON_DATA: ESP_LOGI(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len); if (!esp_http_client_is_chunked_response(evt->client)) { printf("%.*s", evt->data_len, (char*)evt->data); } case HTTP_EVENT_ON_FINISH: ESP_LOGI(TAG, "HTTP_EVENT_ON_FINISH"); break; case HTTP_EVENT_DISCONNECTED: ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED"); break; } } esp_http_client_config_t config = { .url = "http://your_api_url", .event_handler = http_event_handler, }; 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)); } else { ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err)); }
無論你選擇什么方式獲取JSON數據,都需要了解JSON格式并且解析你獲取到的數據以便后續的數據處理工作。