官术网_书友最值得收藏!

Grabbing the content from a web page

As the last project in this chapter, we are finally going to use the Wi-Fi connection of the chip to grab the content of a page. We will simply use the www.example.com page, as it's a basic page largely used for test purposes.

This is the complete code for this project:

// Import required libraries
#include <ESP8266WiFi.h>

// WiFi parameters
constchar* ssid = "your_wifi_network";
constchar* password = "your_wifi_password";

// Host
constchar* host = "www.example.com";

void setup() {
// Start Serial
Serial.begin(115200);

// 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());
}

int value = 0;

void loop() {

Serial.print("Connecting to ");
Serial.println(host);

// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
  }

// This will send the request to the server
client.print(String("GET /") + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  delay(10);

// Read all the lines of the reply from server and print them to Serial
while(client.available()){
    String line = client.readStringUntil('\r');
Serial.print(line);
  }

Serial.println();
Serial.println("closing connection");
  delay(5000);

}

The code is really basic: we first open a connection to the example.com website, and then send a GET request to grab the content of the page. Using the while(client.available()) code, we also listen for incoming data, and print it all inside the Serial monitor.

You can now copy this code and paste it into the Arduino IDE. Then, upload it to the board using the instructions from Chapter 1, Getting Started with the ESP8266, in the section Connecting Your Module to Your Wi-Fi Network. This is what you should see in the Serial monitor:

This is basically the content of the page, in pure HTML code.

主站蜘蛛池模板: 富锦市| 华容县| 普格县| 怀集县| 乌恰县| 宜都市| 师宗县| 高雄市| 宿松县| 安阳市| 乡城县| 克拉玛依市| 吴江市| 昌图县| 宁波市| 呼玛县| 威宁| 榆中县| 延安市| 安溪县| 新竹县| 涪陵区| 汉阴县| 辉县市| 西乌| 瑞丽市| 岱山县| 楚雄市| 三明市| 尼玛县| 迁西县| 海南省| 赤城县| 华容县| 兴义市| 临西县| 孙吴县| 兰州市| 朝阳县| 龙海市| 东阿县|