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

相关推荐
谁刺我心4 天前
Arduino开发ESP32连接手机热点【适合新手】
wifi·esp32连接手机热点
胡斌附体10 天前
springbatch使用记录
数据库·接口·shell·命令·批量·springbatch·并发抽取
aitav010 天前
⚡ WSL2 搭建 s5p6818 Linux 嵌入式开发平台 (part 3):Wifi驱动移植、ssh移植、e2fsprogs移植
linux·wifi·ssh·嵌入式·e2fsprogs
闲人编程11 天前
使用Django从零开始构建一个个人博客系统
后端·python·django·接口·restful·web·个人博客
星野云联AIoT技术洞察13 天前
OpenMQTTGateway 技术全解:统一多协议到 MQTT 的开源网关
lora·esp32·智能家居·ble·ir·iot网关·openmqttgateway
Einstenn14 天前
f1c100s tina usb 接口 rtl8723du模组移植调试
驱动开发·wifi·rtl8723
JZZC216 天前
11.路由器的接口及其相关知识(2025年9月25日)
计算机网络·接口·路由器·ensp·物理层
Anonymousgirls20 天前
正点原子小智BOX0/BOX2 产品使用视频表情功能
学习·esp32·小智ai·视频表情
STCNXPARM1 个月前
深度剖析Linux内核无线子系统架构
linux·运维·系统架构·wifi·无线子系统
朱自清的诗.1 个月前
使用python脚本储存mosquito服务器数据到sqlite
python·单片机·sqlite·esp32