HTTPS Network Invocation on Arduino
Some Arduino boards are able to make SSL TCP/IP network connections. For example, the Arduino Nano 33 IoT device has this ability when the WiFiNINA library is used. From this library, a project might open an SSL connection as follows;
WiFiClient wifi
if (wifi.connectSSL(someHost, 443)) {
doSomething(wifi);
wifi.stop(); // disconnect
} else {
Serial.println("unable to connect to the server");
}
Another library, ArduinoHttpLibrary is able to make HTTP requests from a TCP/IP network connection. This library accepts the Arduino base class Client
as a means of specifying the network mechanic but Client
has connect(...)
but no connectSSL(..)
so cannot connect using SSL. However there is a means of getting ArduinoHttpLibrary
to accept an already connected Client
.
void doSomething(WiFiClient wifi) {
String payload = ...
HttpClient httpClient = HttpClient(wifi, someHost, 443);
httpClient.connectionKeepAlive(); // key to using the existing connection
httpClient.beginRequest();
httpClient.sendHeader("Content-Type", "application/x-www-form-urlencoded");
httpClient.sendHeader("Connection", "close");
httpClient.sendHeader("Content-Length", payload.length());
httpClient.beginBody();
httpClient.print(payload);
httpClient.endRequest();
int statusCode = httpClient.responseStatusCode();
if (2 != statusCode / 100) {
...
}
}
The key is to invoke the method connectionKeepAlive()
method on the instance of the HttpClient
class prior to using it. This will allow the HttpClient
to use the already connected WiFiClient
which was connected using SSL.