【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数据进行了解析,这里可以参考一下:

相关推荐
@PHARAOH2 天前
HOW - 服务接口超时时间和建议策略
前端·接口·接口超时
__Witheart__2 天前
RK Android11 WiFi模组 AIC8800 驱动移植流程
android·wifi·3568·rockchip·aic8800
xiaohai@Linux3 天前
ESP32 在IDF_V5.3.1版本下实现AP无线热点模式!(带WIFI事件处理)
c语言·嵌入式硬件·tcp/ip·wifi·esp32
乐鑫科技 Espressif3 天前
解锁 AIoT 无限可能,乐鑫邀您共赴 Embedded World 2025
esp32·wi-fi·iot·乐鑫科技·embedded world
蟹至之5 天前
类和对象(5)——抽象类和接口
java·接口·类和对象·抽象类
深圳启明云端科技7 天前
ESP32无线Wi-Fi蓝牙方案,设备智能连接控制,物联网通信应用
物联网·esp32·芯片·乐鑫·模组·无线方案
galaxycraft8 天前
Kali linux搭建wifi绵羊墙
wifi·绵羊墙
PassLink_11 天前
ESP32S3(主模式) 与 STM32(从模式) 进行SPI全双工通信
stm32·单片机·嵌入式硬件·esp32·spi
生活最重要(ง •̀_•́)ง13 天前
[ESP32:Vscode+PlatformIO]添加第三方库 开源库 与Arduino导入第三方库的区别
esp32·arduino·第三方库·开源库·platformio
lihan_freak15 天前
java中的抽象类和接口
java·开发语言·接口·抽象类