Search code examples
arduinoesp8266nodemcuget-request

Sending GET Request with NodeMCU ESP8266


I'm trying to send a standard http GET request to my website using the NodeMCU example client code however for some reason it is not working.

If I type into my browser: snackrefill.com/GetData.php?username=aaaa&pin=bbbb&cost=cccc then it will successfully connect with the php script and save a data base entry.

The problem is that when I try to do the same using the NodeMCU module it does not work. it seems to be connecting to WiFi and the server just fine but when it sends the request nothing seems to happen.

Am I structuring my request wrong?

#include <ESP8266WiFi.h>

const char* ssid     = "BELL473";
const char* password = "XXXXXXX";

const char* host = "ns8451.hostgator.com";

void setup() {
  Serial.begin(115200);
  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); //works!

  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() {
  delay(5000);
  ++value;

  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)) { //works!
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/GetData.php";
  url += "?username=";
  url += "aaaa";
  url += "&pin=";
  url += "bbbb";
  url += "&cost=";
  url += "cccc";

  Serial.print("Requesting URL: ");
  Serial.println(url);

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

  Serial.println();
  Serial.println("closing connection");
}

Solution

  • The reason it was not sending was because the host was wrong, i was pointing to my website nameserver when i should have pointed it to the regular website name. I changed const char* host = "ns8451.hostgator.com"; to const char* host = "snackrefill.com"; and now it works!