解决从 Arduino MKR1010 发布到 IFTTT webhook 的问题

Solve issue POSTING to webhook for IFTTT from Arduino MKR1010

我打算发出 post 请求来触发 IFTTT webhook 操作。我正在使用 MKR1010 开发板。我能够连接到网络并使用云集成打开和关闭连接的 LED。

代码如下,但不触发web hook。我可以手动将网址粘贴到浏览器中,这会触发网络挂钩。当代码被 post 编辑时,它 returns 出现 400 错误请求错误。

以下代码中的密钥已替换为虚拟值。

有人知道为什么这没有触发网络挂钩吗? / 你能解释一下为什么 post 请求被服务器拒绝了吗?只要它被发送,我什至不需要读取服务器的响应。

谢谢

// ArduinoHttpClient - Version: Latest 
#include <ArduinoHttpClient.h>


#include "thingProperties.h"


#define LED_PIN 13
#define BTN1 6

char serverAddress[] = "maker.ifttt.com";  // server address
int port = 443;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);


// variables will change:
int btnState = 0;         // variable for reading the pushbutton status
int btnPrevState = 0;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500); 

  // Defined in thingProperties.h
  initProperties();

  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);

  /*
     The following function allows you to obtain more information
     related to the state of network and IoT Cloud connection and errors
     the higher number the more granular information you’ll get.
     The default is 0 (only errors).
     Maximum is 4
 */
  setDebugMessageLevel(2);
  ArduinoCloud.printDebugInfo();

  // setup the board devices
  pinMode(LED_PIN, OUTPUT);
  pinMode(BTN1, INPUT);


}

void loop() {
  ArduinoCloud.update();
  // Your code here 
  // read the state of the pushbutton value:

btnState = digitalRead(BTN1);
if (btnPrevState == 0 && btnState == 1) {
 led2 = !led2;
 postrequest();
}
  digitalWrite(LED_PIN, led2);

btnPrevState = btnState;

}



void onLed1Change() {
  // Do something

   digitalWrite(LED_PIN, led1);
    //Serial.print("The light is ");
    if (led1) {
        Serial.println("The light is ON");
    } else {
    //    Serial.println("OFF");
    }


}

void onLed2Change() {
  // Do something

  digitalWrite(LED_PIN, led2);
}


void postrequest() {
  //    String("POST /trigger/btn1press/with/key/mykeyhere")
 Serial.println("making POST request");
  String contentType = "/trigger/btn1press/with/key";
  String postData = "mykeyhere";

  client.post("/", contentType, postData);

  // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);

    }

为什么要发出 POST 请求并在 POST 正文中发送密钥?浏览器发送 GET 请求。会是

client.get("/trigger/btn1press/with/key/mykeyhere");

在HttpClient中post()第一个参数是'path',第二个参数是contentType(例如"text/plain"),第三个参数是HTTP的主体POST 请求。

所以你的post应该看起来像

client.post("/trigger/btn1press/with/key/mykeyhere", contentType, postData);