Skip to main content

Wi-Fi HTTPS POST request

What this example shows​

Sending an HTTPS POST request with a small JSON body ({"title":"Hello Inkplate"}) to the JSONPlaceholder test API, every 10 seconds, and printing the status code and response in the Serial Monitor. JSONPlaceholder is a fake API, so the response looks real but the example notes that nothing is stored.

You need your Wi-Fi name (ssid) and password (pass). The test API needs no key, but a real API may want authentication headers such as keys or tokens, which you would add with addHeader(). The sketch also uses the ArduinoJson library, so install it in the Arduino IDE first.

Example code​

Trimmed from Inkplate10_HTTPS_POST_Request.ino: the file header comment is removed, the sketch is otherwise unchanged. ssid and pass are placeholders that you replace.

Select Board
Inkplate10_HTTPS_POST_Request.ino
// Next 3 lines are a precaution, you can ignore those, and the example would also work without them
#if !defined(ARDUINO_INKPLATE10) && !defined(ARDUINO_INKPLATE10V2)
#error \
"Wrong board selection for this example, please select e-radionica Inkplate10 or Soldered Inkplate10 in the boards menu."
#endif

// Include needed libraries
#include "ArduinoJson.h"
#include "HTTPClient.h"
#include "Inkplate.h"
#include "WiFi.h"
#include <WiFiClientSecure.h>

// Enter your WiFi credentials
const char *ssid = "";
const char *pass = "";

// Specify the API URL to send a POST request
const char *apiUrl = "https://jsonplaceholder.typicode.com/posts";

// Specify the delay time between 2 POST requests in milliseconds
#define DELAY_BETWEEN_REQUESTS 10000

// Create objects from included libraries
WiFiClientSecure client;
HTTPClient http;
Inkplate display(INKPLATE_1BIT); // Create object on Inkplate library and set library to work in monochrome mode

void setup()
{
// Init serial communication
Serial.begin(115200);

// Init the display
display.begin();

// Clear the display and print message
display.clearDisplay();
display.setTextColor(BLACK);
display.setTextSize(8);
display.printf("HTTPS POST \nRequest example\n");

display.setTextSize(6);
display.printf("\nOpen Serial Monitor at \n115200 baud rate to see \nwhat's happening");
display.display();

// Connect to WiFi
WiFi.begin(ssid, pass);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.println();
Serial.print("Connected to WiFi with IP address ");
Serial.println(WiFi.localIP());

// Use https but don't use a certificate
client.setInsecure();
}

void loop()
{
// Init HTTP client with secure wifi client and the API URL
http.begin(client, apiUrl);

// Add header. In your case maybe you must add more depending on your API
http.addHeader("Content-Type", "application/json");

// Create a JSON document for serializing data
const size_t CAPACITY = JSON_OBJECT_SIZE(1);
StaticJsonDocument<CAPACITY> doc;

// Convert the JSON document to a JSON object in order to add data
JsonObject object = doc.to<JsonObject>();

// Add data in the JSON object
object["title"] = "Hello Inkplate";

// Serialize the JSON object with your data to a JSON document for sending
char jsonOutput[128];
serializeJson(doc, jsonOutput);

// Send the POST request and save returned code
int httpCode = http.POST(String(jsonOutput));

// If the code is smaller than 0, something went wrong
if (httpCode > 0)
{
// Get the string returned by the HTTPS request and print the response
String payload = http.getString();
Serial.println("Status code: " + String(httpCode));
Serial.println(payload);

// End connection
http.end();
}
else
{
Serial.println("Error on HTTPS request");
}

// Wait for sending next request
delay(DELAY_BETWEEN_REQUESTS);
}

Functions used​

WiFiClientSecure()returns None

Creates a client for HTTPS connections. Part of the ESP32 Arduino core.

ReturnsDeclaration; no return value.

HTTPClient()returns None

Creates an HTTP client object. Part of the ESP32 Arduino core.

ReturnsDeclaration; no return value.

Inkplate(uint8_t mode)returns None

Creates the display object. The mode picks how pixels are stored: `INKPLATE_1BIT` is black and white, which is what the sketches on this page use.

ReturnsConstructor; no return value.

Parameters

TypeNameDescription
uint8_tmodeDisplay mode, INKPLATE_1BIT here.
Serial.begin(unsigned long baud)returns void

Starts serial communication at the given speed. The sketch uses 115200.

ReturnsNothing.

Parameters

TypeNameDescription
unsigned longbaudBaud rate.
display.begin()returns void

Initializes the Inkplate library and its peripherals and clears the frame buffer. Call it once in `setup()`; later calls are ignored.

ReturnsNothing.

display.clearDisplay()returns void

Clears the frame buffer. The screen itself does not change until you call `display()` or `partialUpdate()`.

ReturnsNothing.

display.setTextColor(uint16_t c)returns void

Sets the text color with a transparent background. Comes from the Adafruit GFX base class.

ReturnsNothing.

Parameters

TypeNameDescription
uint16_tcText color, for example BLACK.
display.setTextSize(uint8_t s)returns void

Sets the text scale. 1 is the base size, 2 is twice as big, and so on. The function comes from the Adafruit GFX base class the library builds on.

ReturnsNothing.

Parameters

TypeNameDescription
uint8_tsText scale factor.
display.printf(const char *format, ...)returns size_t

Prints formatted text at the cursor, using the usual `printf` format syntax. Comes from the Arduino `Print` class.

ReturnsNumber of bytes written.

Parameters

TypeNameDescription
const char *formatFormat string, for example with \n for new lines.
display.display(bool _leaveOn = 0)returns void

Sends the frame buffer to the e-paper panel and refreshes it.

ReturnsNothing.

Parameters

TypeNameDescription
bool_leaveOnOptional. If set to 1, the panel supply stays on after the refresh. Defaults to 0.
WiFi.begin(const char *ssid, const char *pass)returns wl_status_t

Starts connecting to a Wi-Fi network. It returns right away; check `WiFi.status()` to see when the connection is up. Part of the ESP32 Arduino core.

ReturnsConnection status.

Parameters

TypeNameDescription
const char *ssidName of the Wi-Fi network.
const char *passPassword of the Wi-Fi network.
Serial.println(value)returns size_t

Prints text or a number to the Serial Monitor followed by a line break.

ReturnsNumber of bytes written.

Parameters

TypeNameDescription
variousvalueA string or number to print.
Serial.print(value)returns size_t

Prints text or a number to the Serial Monitor without a line break.

ReturnsNumber of bytes written.

Parameters

TypeNameDescription
variousvalueA string or number to print.
WiFi.status()returns wl_status_t

Returns the current Wi-Fi connection state. `WL_CONNECTED` means the connection is up. Part of the ESP32 Arduino core.

ReturnsThe connection status.

delay(unsigned long ms)returns void

Pauses the sketch for the given number of milliseconds. Arduino core function.

ReturnsNothing.

Parameters

TypeNameDescription
unsigned longmsTime to wait in milliseconds.
WiFi.localIP()returns IPAddress

Returns the IP address Inkplate got from the network. Part of the ESP32 Arduino core.

ReturnsThe local IP address.

client.setInsecure()returns void

Makes `WiFiClientSecure` skip checking the server certificate. Convenient for tests, not recommended for production according to the example.

ReturnsNothing.

http.begin(WiFiClient &client, const char *url)returns bool

Prepares an `HTTPClient` request to the URL, using the client you pass in. The example passes a `WiFiClientSecure` for HTTPS.

Returns`true` if the URL was accepted.

Parameters

TypeNameDescription
WiFiClient &clientThe client that carries the connection.
const char *urlAddress to request.
http.addHeader(const String &name, const String &value)returns void

Adds a header to the request.

ReturnsNothing.

Parameters

TypeNameDescription
const String &nameHeader name, for example Content-Type.
const String &valueHeader value.
JSON_OBJECT_SIZE(1)returns size_t

ArduinoJson macro that gives the memory needed for an object with the given number of members. Here it sizes a document for one member.

ReturnsBytes needed.

Parameters

TypeNameDescription
intnNumber of members.
StaticJsonDocument<CAPACITY> docreturns None

Creates an ArduinoJson document of fixed size on the stack. `CAPACITY` is the size in bytes.

ReturnsDeclaration; no return value.

doc.to<JsonObject>()returns JsonObject

Clears the ArduinoJson document and turns it into an empty JSON object you can add values to.

ReturnsThe empty object.

serializeJson(doc, jsonOutput)returns size_t

Writes the JSON document as text into a character buffer. Part of the ArduinoJson library.

ReturnsNumber of bytes written.

Parameters

TypeNameDescription
JsonDocumentdocThe document to serialize.
char[]jsonOutputThe buffer that receives the text.
http.POST(String payload)returns int

Sends the prepared request as an HTTP POST with the given body.

ReturnsHTTP status code, or a negative number if the request failed.

Parameters

TypeNameDescription
StringpayloadThe request body.
http.getString()returns String

Returns the response body as a text string.

ReturnsThe response body.

http.end()returns void

Ends the `HTTPClient` connection and frees its resources.

ReturnsNothing.

JsonObject()returns None

ArduinoJson type for a JSON object. The sketch gets one from `doc.to<JsonObject>()` and then sets values on it by key. Part of the ArduinoJson library, not the Inkplate library.

ReturnsType declaration; no return value.

What to expect​

The display shows "HTTPS POST Request example" and a reminder to open the Serial Monitor at 115200 baud. The rest is in the Serial Monitor:

Serial MonitorAutoscrollShow timestampNewline115200 baud
Message (Enter to send message to the board)
Connecting to WiFi
.....
Connected to WiFi with IP address <IP address>
Status code: <status code>
<response body>

<IP address> is the address your router assigns to the board. <status code> is the HTTP status code from jsonplaceholder.typicode.com, and <response body> is the text the server sends back.

The Status code: line and the response body repeat every 10 seconds. If the request fails the sketch prints "Error on HTTPS request" instead.

The sketch calls client.setInsecure(), so it does not check the server certificate. The example says this suits demos and tests but is not recommended for production. To check the certificate, see the HTTPS with certificate example.