HTTP POST from ESP32 to Google Chat Webhook - Connection Refused

80 Views Asked by At

I'm using Wokwi.com to create a simulation where an ESP32 connect to a WiFi and try to send a message to Google Chat webhook. But I always got a 'connection refused' error.

I'm using this HTTP library

This is the code in Wokwi.com

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* googleChatWebhook = "https://chat.googleapis.com/v1/spaces/mySpace/messages?key=myKey&token=myToken";

void setup() {
  Serial.begin(115200);
  WiFi.begin("Wokwi-GUEST", "", 1);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");


}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    WiFiClientSecure client; 
    // Your message payload
    String message = "{'text': 'Hello, this is a test message!'}";

    boolean Result = http.begin(client, googleChatWebhook);
    Serial.println(Result);
    http.addHeader("Content-Type", "application/json");

    int httpResponseCode = http.POST(message);

    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);

    if (httpResponseCode > 0) {
      String payload = http.getString();
      Serial.println(payload);
    } else {
      Serial.print("HTTP Request failed. Error: ");
      Serial.println(http.errorToString(httpResponseCode));
    }

    http.end();
  }

  delay(5000);  // Send a message every 5 seconds (adjust as needed)
}

Error message: HTTP Response code: -1 HTTP Request failed. Error: connection refused

It's a success when I tried it on Postman. Auth type is 'No Auth' the body is raw. Please see the attached image. Postman

I was thinking that maybe I need to set the auth type to No Auth, but don't know how.

1

There are 1 best solutions below

1
thepirat000 On

Have you tried adding client.setInsecure(); before your http.begin?.

Also, you probably want to set http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); so the client follow redirects from the google API response.

I use the following code to communicate with google scripts from an ESP32:

https://github.com/thepirat000/SpyCam/blob/main/http_client.cpp