How to send HTTPS GET request using NODEMCU

Viewed 5936

How do you send a HTTPS - GET/POST request using Nodemcu - Arduino code.

I've ben searching days for a working example that sends a GET request using HTTPS protocol to a website and all examples that I've found were unsuccessful.

I hope it will help others too!

1 Answers

Here is the link that helped me

To make the examples work with the HTTPS protocol you would have to use the WiFiClientSecure library and call the client.setInsecure() function of the WiFiClientSecure's object you have.

Here is a fully working code:

#include <ESP8266WiFi.h>

const char* ssid     = "WIFI_SSID";
const char* password = "WIFI_PASS";

const char* host = "DOMAIN_NAME"; // only google.com not https://google.com

void setup() {
  Serial.begin(115200);
  delay(10);

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

void loop() {
  delay(5000);

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

  // Use WiFiClient class to create TCP connections
  WiFiClientSecure client;
  const int httpPort = 443; // 80 is for HTTP / 443 is for HTTPS!
  
  client.setInsecure(); // this is the magical line that makes everything work
  
  if (!client.connect(host, httpPort)) { //works!
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/arduino.php";
  url += "?data=";
  url += "aaaa";


  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");
}
Related