首页 > 解决方案 > 解决从 Arduino MKR1010 发布到 IFTTT 的 webhook 的问题

问题描述

我的目标是发出一个发布请求以触发 IFTTT webhook 操作。我正在使用 MKR1010 板。我能够连接到网络并使用云集成打开和关闭连接的 LED。

代码如下,但不会触发web hook。我可以在浏览器中手动粘贴网址,这会触发网络挂钩。发布代码时,它会返回 400 bad request 错误。

在下面的代码中,密钥已被替换为虚拟值。

有人知道为什么这不会触发网络钩子吗?/你能解释一下为什么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);

    }

标签: postarduinoiotifttt

解决方案


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

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

在 HttpClientpost()中,第一个参数是 'path',第二个参数是 contentType(例如“text/plain”),第三个参数是 HTTP POST 请求的正文。

所以你post应该看起来像

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

推荐阅读