【Ardiuno】使用ESP32网络功能调用接口数据(图文)

接着上文连通wifi后,我们通过使用HTTPClient库进行网络相关操作,这里我们通过http协议进行接口调用。

为了简化操作,这里使用了本地服务器上的文件作为接口,正常操作时会调用接口后,将服务器返回的数据进行解析,现在一般的接口返回json数据为主,需要引用ArduinoJson.h。

复制代码
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid     = "Xiaomi";
const char* password = "XIAOFEIYU666";

void setup()
{
    Serial.begin(9600);
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to:");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    //==========================================================================
    pinMode(2, OUTPUT);
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(2, LOW);
    delay(500); 

    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(2, LOW);
    delay(500); 

    digitalWrite(2, HIGH);
    delay(2500);
    digitalWrite(2, LOW);

    //==========================================================================    
    HTTPClient http;                                      //创建HTTPClient对象
    String url = "http://192.168.3.6:8088/robots.txt";
    http.begin(url);                                      //指定访问 URL
        
    int http_code = http.GET();                           //接收HTTP响应状态码
    Serial.printf("HTTP状态码:%d\n", http_code);
        
    String response = http.getString();                   //获取响应正文
    Serial.print("响应数据:");
    Serial.println(response);
        
    http.end();                                           //关闭连接
}

void loop(){
}

上传程序后,使用串口监视器查看结果,可以看到http调用成功返回200状态码,然后输出两行数据,这两行数据即为服务器上的文件内容(以此代替api返回的json数据)。

通过以上实验,我们已经可以正常操作esp32连接网络调用相关接口,通过进一步解析即可获取我们需要的数据。

借鉴例子中调用的天气服务接口,对返回json数据进行了解析,这里可以参考一下:

相关推荐
星野云联AIoT技术洞察7 小时前
ESP32-C3、ESP32-S3、ESP32-C6 应该怎么选:面向定制固件项目的芯片判断
esp32·乐鑫·esp32-s3·matter·esp32-c3·esp32-c6·wi-fi 6
乐鑫科技 Espressif12 小时前
乐鑫联合 Bosch Sensortec(博世传感器)推出磁感应交互方案
esp32·交互·乐鑫科技·博世·c磁感应·交互方案
凌盛羽2 天前
ESP32-S3定时器组Timer Group0/1的使用
stm32·单片机·嵌入式硬件·链表·esp32·定时器
欢乐熊嵌入式编程3 天前
用 ESP32 + WiFi 做远程控制插座(从原理到实战)
单片机·wifi·智能路由器·esp32·远程控制插座
π同学3 天前
ESP-IDF+vscode开发ESP32第四讲——I2C
vscode·esp32·i2c
凌盛羽3 天前
在MDK-ARM编译后用python解析map文件在编译窗口输出Flash和RAM使用及剩余情况
arm开发·python·stm32·单片机·mysql·链表·esp32
@haihi6 天前
ESP32 MQTT示例解析
开发语言·网络·mqtt·github·esp32
深念Y7 天前
技术选型系列文章(四):从任务清单到接口规格
ai·接口·软件工程·api·agent·任务
乐鑫科技 Espressif7 天前
乐鑫发布 ESP32-S31:高性能多协议双核 RISC-V,面向 AI 智能交互
人工智能·mcu·esp32·乐鑫科技
π同学8 天前
ESP-IDF+vscode开发ESP32第三讲——UART
vscode·esp32·uart·esp-idf