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

Grabbing the content from a web page

To illustrate how the WiFi101 library is working on the MKR1000 board, we are now going to use it to grab the content of a web page, and display the result inside the Serial monitor.

Getting ready

You do not need any extra steps here, simply make sure that you have the WiFi101 library installed.

How to do it...

Let's now see the sketch for this recipe. As it is really similar to the sketch of the previous recipe, I will only highlight the main pieces of code that were added here:

  1. You first need to define which page we are going to grab. Here, I will just make the board grab the www.example.com page:
    char server[] = "www.example.com";
  2. Then, we need to create an instance of a Wi-Fi client:
    WiFiClient client;
  3. Then, inside the setup() function of the sketch, we connect to the server we defined earlier, and request the Web page:
    // Connect to server
      if (client.connect(server, 80)) {
        Serial.println("connected to server");
        
        // Make a request:
        client.println("GET / HTTP/1.1");
        client.println("Host: www.example.com");
        client.println("Connection: close");
        client.println();
      }
  4. Inside the loop() function of the sketch, we then read the data coming back from the server, and print it inside the Serial port:
    while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }
  5. We then stop the connection with the following piece of code:
    // Stop the connection
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting from server.");
        client.stop();
    
        // do nothing forevermore:
        while (true);
      }
  6. It's now time to try this sketch! First, grab the code from the GitHub repository of this book, and then change your Wi-Fi credentials inside the code. Then, upload the code to the board, and open the Serial monitor. This is what you should see:

If you can see that, it means that the board has successfully grabbed the content of the web page and displayed it inside the Serial monitor.

How it works...

The sketch uses the Wi-Fi client of the WiFi101 library, which is a very powerful object that we will use again in several chapters of this book.

See also

I now recommend checking the next recipe, in which you will actually learn how to use the Wi-Fi client library to send data to a cloud server.

主站蜘蛛池模板: 海口市| 松潘县| 柏乡县| 高陵县| 福海县| 宝清县| 咸宁市| 呼伦贝尔市| 客服| 成武县| 贵阳市| 金平| 自贡市| 贡觉县| 盐津县| 芦山县| 禹城市| 枝江市| 光泽县| 兰州市| 麻江县| 荣昌县| 襄樊市| 伽师县| 桂平市| 合川市| 张家港市| 凌海市| 若羌县| 东平县| 土默特右旗| 朝阳区| 荔浦县| 密山市| 广灵县| 洛宁县| 普宁市| 肥乡县| 合江县| 日喀则市| 克东县|