13. ESP32-HTTPClient(Arduino)

使用ESP32 Arduino框架的HTTPClient库进行HTTP请求

在ESP32开发里,网络通信是挺重要的一部分,你可能需要从服务器拿数据啊,或者把传感器数据发到云端什么的。不过别担心,ESP32 Arduino框架给我们提供了HTTPClient库,让HTTP请求轻松简单。这篇文章就是来告诉你怎么在ESP32上利用HTTPClient库做HTTP请求的。

步骤一:包含必要的库

首先,在你的Arduino项目中,你需要包含HTTPClient库。打开Arduino IDE,点击顶部菜单栏中的"工具",然后选择"管理库"。在库管理器中搜索"HTTPClient",点击安装。
在这里插入图片描述

步骤二:初始化WiFi连接

在进行HTTP请求之前,需要确保ESP32已连接到WiFi网络。使用WiFi库来初始化WiFi连接,对WiFi库不了解的博友可以看一下这篇文章 7. ESP32-WIFI(Arduino)

#include <WiFi.h>

const char* ssid = "你的WiFi网络名称";
const char* password = "你的WiFi网络密码";

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("正在连接到WiFi...");
    }
    Serial.println("已连接到WiFi网络");
}

步骤三:发起HTTP请求

一旦连接到WiFi网络,就可以使用HTTPClient库来发起HTTP请求了。

发起get请求

下面是如何详细发起HTTP get请求的:

  1. 创建HTTPClient对象: 首先,你需要创建一个HTTPClient对象。这个对象将负责处理HTTP请求和响应。

    HTTPClient http;
    
  2. 开始HTTP会话: 使用HTTPClient对象的begin()方法来指定你要访问的URL。这个URL可以是一个完整的URL,比如http://example.com/data,或者是一个IP地址,比如http://192.168.1.100/data

    http.begin("http://example.com/data");
    
  3. 选择HTTP方法: HTTP请求有多种方法,最常见的是GET和POST。GET方法用于从服务器获取数据,而POST方法用于向服务器发送数据。在这个例子中,我们使用GET方法获取数据。

    int httpResponseCode = http.GET();
    
  4. 处理响应: 一旦HTTP请求发送成功,服务器将会返回一个HTTP响应码。通常情况下,200表示成功。你可以使用http.GET()的返回值来获取响应码。

    if (httpResponseCode > 0) {
        // HTTP请求成功
    } else {
        // HTTP请求失败
    }
    
  5. 获取服务器响应: 如果HTTP请求成功,你可以使用http.getString()来获取服务器返回的数据。如果服务器返回的是JSON格式的数据,你可以使用ArduinoJson库的方法来解析它 关于ArduinoJson的详细内容可以看我的另一篇文章 ESP32-JSON(Arduino)

    String payload = http.getString();
    
  6. 结束HTTP会话: 当HTTP请求完成后,记得调用http.end()来结束HTTP会话,释放资源。

    http.end();
    
#include <HTTPClient.h>

const char* serverURL = "http://example.com/data"; // 更换为你的服务器地址

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("正在连接到WiFi...");
    }
    Serial.println("已连接到WiFi网络");

    HTTPClient http;

    Serial.print("正在发送HTTP GET请求到:");
    Serial.println(serverURL);
    http.begin(serverURL);

    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
        Serial.print("HTTP响应码:");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println("服务器响应:");
        Serial.println(payload);
    } else {
        Serial.print("HTTP GET请求失败,错误码:");
        Serial.println(httpResponseCode);
    }

    http.end(); // 结束HTTP连接
}

void loop() {
    // 可选的其他代码
}

发起POST请求

不论是POST请求还是get请求,大致步骤都是相同的。下面的示例展示了如何发送一个POST请求,并接收并解析服务器返回的JSON格式数据。

  1. 创建HTTPClient对象并初始化会话:

    HTTPClient http;
    http.begin(serverURL);
    
  2. 设置请求头:

    http.addHeader("Content-Type", "application/json");
    

    "Content-Type": "application/json" 告诉服务器请求体的格式是JSON。

  3. 创建JSON请求体:

    StaticJsonDocument<200> jsonDoc;
    jsonDoc["key1"] = "value1";
    jsonDoc["key2"] = "value2";
    String requestBody;
    serializeJson(jsonDoc, requestBody);
    
  4. 发送POST请求并获取响应码:

    int httpResponseCode = http.POST(requestBody);
    
  5. 处理响应:

    if (httpResponseCode > 0) {
        String response = http.getString();
        // 解析并处理JSON响应
    } else {
        // 处理请求失败的情况
    }
    
  6. 解析JSON响应:

    StaticJsonDocument<200> responseJson;
    DeserializationError error = deserializeJson(responseJson, response);
    if (!error) {
        const char* value = responseJson["key"];
    }
    
  7. 结束HTTP会话:

    http.end();
    
const char* serverURL = "http://example.com/api"; // 替换为你的服务器地址

void sendPostRequest() {
    if (WiFi.status() == WL_CONNECTED) {
        HTTPClient http;

        http.begin(serverURL);
        http.addHeader("Content-Type", "application/json"); // 设置请求头

        // 创建JSON请求体
        StaticJsonDocument<200> jsonDoc;
        jsonDoc["key1"] = "value1";
        jsonDoc["key2"] = "value2";
        String requestBody;
        serializeJson(jsonDoc, requestBody);

        // 发送POST请求
        int httpResponseCode = http.POST(requestBody);

        if (httpResponseCode > 0) {
            String response = http.getString();
            Serial.print("HTTP响应码:");
            Serial.println(httpResponseCode);
            Serial.println("服务器响应:");
            Serial.println(response);

            // 解析服务器返回的JSON响应
            StaticJsonDocument<200> responseJson;
            DeserializationError error = deserializeJson(responseJson, response);
            if (error) {
                Serial.print("解析JSON失败:");
                Serial.println(error.c_str());
                return;
            }

            // 提取数据并存储
            const char* value = responseJson["key"]; // 根据JSON中的键提取值
            Serial.print("从服务器返回的值是:");
            Serial.println(value);
        } else {
            Serial.print("HTTP POST请求失败,错误码:");
            Serial.println(httpResponseCode);
        }

        http.end(); // 结束HTTP连接
    } else {
        Serial.println("WiFi未连接");
    }
}

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("正在连接到WiFi...");
    }
    Serial.println("已连接到WiFi网络");

    // 发送POST请求
    sendPostRequest();
}

void loop() {
    // 可选的其他代码
}

结论

在ESP32 Arduino框架里,用HTTPClient库发HTTP请求超级简单又高效😄。就几个简单的步骤,你就能轻松地发起GET和POST请求,处理服务器的响应,连响应头和响应正文都能读📖。HTTPClient库特别灵活,再加上ArduinoJson库厉害的解析能力🔍,处理HTTP通信变得简直顺手无比👌。这招对物联网应用特别管用🌐,像远程数据收集、设备控制和数据传输之类的💪。

参考资料

下面是一份简单的ESP32-CAM和Arduino的图像检测和识别程序示例,程序利用了Arduino IDE自带的TensorFlow Lite库进行图像分类和识别。这个例子将会使用ESP32-CAM拍摄一张照片,将照片上传到云端进行图像识别,然后将结果显示在串口上。 在开始之前,确保已经安装了Arduino IDE、ESP32开发环境和TensorFlow Lite库。 ``` #include <WiFi.h> #include <WiFiClientSecure.h> #include <HTTPClient.h> #include "esp_camera.h" #include "img_converters.h" #include "Arduino.h" #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" // Replace with your network credentials const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; // Replace with your cloud service URL const char* cloud_url = "https://your_cloud_service.com/image_processing"; // Replace with your cloud service certificate fingerprint const char* cloud_fingerprint = "your_cloud_service_fingerprint"; // Replace with your camera resolution #define CAMERA_WIDTH 640 #define CAMERA_HEIGHT 480 // Initialize the camera void init_camera() { camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = 5; config.pin_d1 = 18; config.pin_d2 = 19; config.pin_d3 = 21; config.pin_d4 = 36; config.pin_d5 = 39; config.pin_d6 = 34; config.pin_d7 = 35; config.pin_xclk = 0; config.pin_pclk = 22; config.pin_vsync = 25; config.pin_href = 23; config.pin_sscb_sda = 26; config.pin_sscb_scl = 27; config.pin_pwdn = 32; config.pin_reset = -1; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 10; config.fb_count = 2; // Initialize the camera esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with error 0x%x", err); return; } } // Take a photo and return the JPEG data String take_photo() { camera_fb_t* fb = NULL; fb = esp_camera_fb_get(); if (!fb) { Serial.println("Camera capture failed"); return ""; } // Convert the photo to JPEG String jpeg; bool ok = frame2jpg(fb, 10, &jpeg, NULL); if (!ok) { Serial.println("JPEG compression failed"); return ""; } // Free the memory esp_camera_fb_return(fb); return jpeg; } // Upload the photo to the cloud and get the result String get_image_result(String image_data) { // Create a secure WiFi client WiFiClientSecure client; client.setFingerprint(cloud_fingerprint); // Make a HTTP POST request to the cloud service HTTPClient http; http.begin(client, cloud_url); http.addHeader("Content-Type", "application/json"); String payload = "{\"image\": \"" + image_data + "\"}"; int http_code = http.POST(payload); if (http_code != HTTP_CODE_OK) { Serial.printf("HTTP POST failed with error %d", http_code); return ""; } // Get the response from the cloud service String response = http.getString(); // Free the resources http.end(); return response; } void setup() { // Disable brownout detector WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // Initialize the serial port Serial.begin(115200); // Connect to WiFi Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(" connected"); // Initialize the camera init_camera(); } void loop() { // Take a photo String image_data = take_photo(); if (image_data == "") { Serial.println("Failed to take a photo"); return; } // Get the image result from the cloud service String result = get_image_result(image_data); if (result == "") { Serial.println("Failed to get the image result"); return; } // Print the result Serial.printf("Image result: %s", result.c_str()); // Delay for 1 second delay(1000); } ``` 这个程序会连接到指定的WiFi网络,然后使用ESP32-CAM拍摄一张照片并将其转换成JPEG格式。然后,程序会将JPEG数据上传到云端的指定URL,等待云端的图像分类和识别服务返回结果。最后,程序会将结果显示在串口上,并等待1秒钟再继续执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宁子希

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值