ESP8266与NodeMCU开发(三)客户端

    xiaoxiao2021-04-18  77

    这一节将讲解如何将ESP8266编程设置为一个网页客户端,访问www.example.com,发送请求并获取返回数据,通过串口打印出来

    流程如下:

    1.首先需要连接上路由器或者任意AP,从而获得能访问外网的途径,这一点在上一章节中已经说明。

    相关代码:

    #define WIFINAME "wifi名称" #define WIFIPW "wifi密码" WiFi.begin(WIFINAME, WIFIPW); 等待ESP8266连接上AP

    while (WiFi.status() != WL_CONNECTED)//try link to router { delay(500); Serial.print("."); }

    2.实例化一个客户端,用以建立http连接,并发送请求

    设置请求网址

    const char* host = "www.example.com";

    实例化

    WiFiClient client; 与服务端建立连接

    client.connect(host, 80)

    向服务端发送请求

    client.print(String("GET /") + "HTTP/1.1\r\n" + "Host:" + host + "\r\n" + "Connection: close\r\n" + "\r\n" );

    3.如果连接建立并且请求发送成功,然后就可以收到由服务端发送的回复,使用一个字符串来保存

    String line = client.readStringUntil('\n');

    4.打印获取的回复讯息

    Serial.println(line);

    从打印结果可以看到,网页头部和主体都提示“HTTP Version Not Supported”,因为HTTP版本较低因此服务端未传送网页布局文件到ESP8266上,但整个通信过程是成功的。

    在实际的编程中需要追加连接成功才发送请求的判断,以防止ESP8266因错误的指令而重启。

    程序整体源代码:

    #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #define WIFINAME "ChinaMobile-45012" #define WIFIPW "wangjinxuan" const char* host = "www.example.com"; void setup() { pinMode(BUILTIN_LED, OUTPUT); Serial.begin(115200); Serial.println(""); WiFi.begin(WIFINAME, WIFIPW);//link to router Serial.print("Connecting.."); while (WiFi.status() != WL_CONNECTED)//try link to router { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected,IP Address:");//connecting succeed Serial.println(WiFi.localIP()); } void loop() { // put your main code here, to run repeatedly: WiFiClient client; Serial.printf("\r\nConnectint to %s ..", host); Serial.println(""); if (client.connect(host, 80)) { Serial.println("Connected!"); Serial.println("Send a request"); client.print(String("GET /") + "HTTP/1.1\r\n" + "Host:" + host + "\r\n" + "Connection: close\r\n" + "\r\n" ); Serial.println("\r\n[Response:]"); while (client.connected()) { while (client.connected()) { if (client.available()) { String line = client.readStringUntil('\n'); Serial.println(line); } } client.stop(); Serial.println("\nClient stop, disconnected"); } } else { Serial.println("connecting failed!"); client.stop(); } delay(8000); }

    参考:https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/client-examples.md#select-a-server

    转载请注明原文地址: https://ju.6miu.com/read-674635.html

    最新回复(0)