Skip to content

Instantly share code, notes, and snippets.

@9SQ
Last active May 20, 2022 04:54
Show Gist options
  • Save 9SQ/200c796672b0f4db173e to your computer and use it in GitHub Desktop.
Save 9SQ/200c796672b0f4db173e to your computer and use it in GitHub Desktop.
Arduino core for esp8266 WiFiClientSecure
#ifdef ESP8266
extern "C" {
#include "user_interface.h"
}
#endif
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
ADC_MODE(ADC_VCC);
WiFiClientSecure client;
const char* host = "example.com";
String ssid = "test_ap";
String pass = "this_is_test";
void setup() {
Serial.begin(115200);
if (wifiConnection()) {
String url = "/api/test/";
String data = "text=Hello ESP8266!&bat=" + ESP.getVcc();
Serial.println("POST to https://" + String(host) + url);
Serial.print("Result(response): ");
Serial.println(httpsPost(url, data));
}
}
void loop() {
}
boolean wifiConnection() {
WiFi.begin(ssid.c_str(), pass.c_str());
int count = 0;
Serial.print("Waiting for Wi-Fi connection");
while ( count < 20 ) {
if (WiFi.status() == WL_CONNECTED) {
Serial.println();
Serial.println("Connected!");
return (true);
}
delay(500);
Serial.print(".");
count++;
}
Serial.println("Timed out.");
return false;
}
String httpsPost(String url, String data) {
if (client.connect(host, 443)) {
client.println("POST " + url + " HTTP/1.1");
client.println("Host: " + (String)host);
client.println("User-Agent: ESP8266/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.println(data);
delay(10);
String response = client.readString();
int bodypos = response.indexOf("\r\n\r\n") + 4;
return response.substring(bodypos);
}
else {
return "ERROR";
}
}
@gchokhon
Copy link

it is not working for me:( Result(response): ERROR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment