从 ESP32 到 Google Chat Webhook 的 HTTP POST - 连接被拒绝

问题描述 投票:0回答:1

我正在使用 Wokwi.com 创建一个模拟,其中 ESP32 连接到 WiFi 并尝试向 Google Chat webhook 发送消息。但我总是收到“连接被拒绝”错误。

我正在使用这个 HTTP 库

这是 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)
}

错误信息: HTTP 响应代码:-1 HTTP 请求失败。错误:连接被拒绝

在Postman上尝试了一下,成功了。身份验证类型为“无身份验证”,主体是原始的。请参阅附图。 Postman

我想也许我需要将身份验证类型设置为“无身份验证”,但不知道如何操作。

http-post webhooks esp32 google-chat
1个回答
0
投票

您是否尝试过在 http.begin 之前添加

client.setInsecure();
?.

此外,您可能想要设置

http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
,以便客户端遵循来自 google API 响应的重定向。

我使用以下代码与 ESP32 中的 google 脚本进行通信:

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

© www.soinside.com 2019 - 2024. All rights reserved.