I'm sending a JSON to my HTTPS REST API, but it's not working. (I'm also sending information to an MQTT broker and to my WhatsApp using a bot, but that part works well).
BOARD: ESP32 DEV MODULE
The code (I errased the sensitive parts like passwords, etc.):
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <PubSubClient.h>
// MONGODB
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
const char *ssid = "";
const char *password = "";
int contconexion;
String url;
// MONGODB
// The REST API endpoint
const char *base_rest_url = "";
// Size of the JSON document. Use the ArduinoJSON JSONAssistant
const int JSON_DOC_SIZE = 384;
String apiKey_1 = "";
String numero_tlf_1 = "";
String str = "";
const char separator = ',';
const int dataLength = 1;
String data[dataLength];
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "";
const char *topic0 = "";
const char *mqtt_username = "";
const char *mqtt_password = "";
const int mqtt_port = ;
WiFiServer server(80);
WiFiClient espClient;
PubSubClient client(espClient);
// MONGO
HTTPClient http;
WiFiClientSecure wifiClientAPI;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED and contconexion < 50) {
++contconexion;
delay(500);
Serial.print(".");
}
if (contconexion < 50) {
Serial.println("");
Serial.print("Successful Connection: ");
Serial.println(WiFi.localIP());
server.begin();
}
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("Client %s connected to the MQTT broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("EMQX MQTT public broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
String stringOne = "Connected";
char Buf[50];
stringOne.toCharArray(Buf, 50);
client.publish(topic, Buf);
client.subscribe(topic0);
}
void loop() {
client.loop();
if (Serial.available()) {
str = Serial.readStringUntil('\n');
for (int i = 0; i < dataLength; i++) {
int index = str.indexOf(separator);
data[i] = str.substring(0, index);
str = str.substring(index + 1);
}
String stringOne = "Subject Registered: " + String(data[0]) + " attended";
char Buf[170];
stringOne.toCharArray(Buf, 170);
client.publish(topic, Buf);
sendPostRequest(String(data[0]));
delay(2000);
message_to_whatsapp(stringOne);
}
}
void message_to_whatsapp(String message) {
url = "https://api.callmebot.com/whatsapp.php?phone=" + numero_tlf_1 + "&text=" + urlencode(message) + "&apikey=" + apiKey_1;
postData();
}
void postData() {
int httpCode; // variable used to get the response http code after calling the API
HTTPClient http; // Declare an object of class HTTPClient
http.begin(url); // begin the HTTPClient object with the generated URL
httpCode = http.POST(url);
if (httpCode == 200) // Check if the response http code is 200
{
Serial.println("Sent to EMQX successfully"); // print message sent ok message
} else // if response HTTP code is not 200 it means there is some error.
{
Serial.println("Not sent to EMQX"); // print error message.
}
http.end(); // After calling the API end the HTTP client object.
}
void callback(char *topic0, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic0);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
String urlencode(String str) // Function used for encoding the URL
{
String encodedString = "";
char c;
char code0;
char code1;
char code2;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == ' ') {
encodedString += '+';
} else if (isalnum(c)) {
encodedString += c;
} else {
code1 = (c & 0xf) + '0';
if ((c & 0xf) > 9) {
code1 = (c & 0xf) - 10 + 'A';
}
c = (c >> 4) & 0xf;
code0 = c + '0';
if (c > 9) {
code0 = c - 10 + 'A';
}
code2 = '\0';
encodedString += '%';
encodedString += code0;
encodedString += code1;
}
yield();
}
return encodedString;
}
// MONGODB
void sendPostRequest(String name) {
char rest_api_url[200];
// Calling our API server
sprintf(rest_api_url, "%sfingerprint/post", base_rest_url);
Serial.println(rest_api_url);
// Create a JSON object with the "name" field
StaticJsonDocument<JSON_DOC_SIZE> jsonDocument;
jsonDocument["name"] = name;
// Serialize the JSON into a string
String jsonData;
serializeJson(jsonDocument, jsonData);
Serial.println("JSON Data...");
Serial.println(jsonData);
// Initialize the HTTP request
http.begin(wifiClientAPI, rest_api_url);
// Set a header to indicate that you are sending JSON
http.addHeader("Content-Type", "application/json");
// Perform the HTTP POST request
int httpResponseCode = http.POST(jsonData);
if (httpResponseCode > 0) {
Serial.print("Successful HTTP POST. Response code: ");
Serial.println(httpResponseCode);
// You can print the server's response if needed
String response = http.getString();
Serial.println(response);
} else {
Serial.print
("Error in POST request. Response code: ");
Serial.println(httpResponseCode);
}
// End the HTTP request
http.end();
}
The error I get is this:
Error in POST request. Response code: -1