Bohdan
Bohdan

Reputation: 581

How to get data from web by NodeMCU

I'm using NodeMCU v3, and can already send some information on its server.

But how can I receive some information from other web pages, let say for beginning, a plain text?

Upvotes: 2

Views: 4297

Answers (1)

sBanda
sBanda

Reputation: 379

You need a HttpClient to communicate with a web server.

Good way to start is to use the HttpClient sample -> ReuseConnection.

This will allow you to make more requests than one.

You can see in Serial Monitor in Arduino IDE to see the response from the request.

Sample code:

Note: replace " http://:/someroute " with the desired http page you want to get.

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;

HTTPClient http;

void setup() {

    USE_SERIAL.begin(115200);
   // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFiMulti.addAP("SSID", "PASSWORD");

    // allow reuse (if server supports it)
    http.setReuse(true);
}

void loop() {
    // wait for WiFi connection
    if((WiFiMulti.run() == WL_CONNECTED)) {

        http.begin("http://<IP>:<Port>/someroute");

        int httpCode = http.GET();
        if(httpCode > 0) {
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                String payload = http.getString();
                USE_SERIAL.println(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(3000);
}

Upvotes: 2

Related Questions