使用Arduino IDE的NodeMCU模块的HTTP POST

时间:2016-11-10 10:49:19

标签: http nodemcu arduino-esp8266

我有一个NodeMCU WiFi模块,我在Arduino IDE中为它编码。我在发送内容时遇到问题,使用POST方法然后阅读页面。我有一个返回两个变量的PHP页面。我的代码如下:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial

ESP8266WiFiMulti WiFiMulti;
HTTPClient http;

void setup() {
    USE_SERIAL.begin(115200);
    // USE_SERIAL.setDebugOutput(true);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for (uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }
    WiFiMulti.addAP("SSID", "PASSWORD");
}

void loop() {
    // wait for WiFi connection

    if ((WiFiMulti.run() == WL_CONNECTED)) {
        HTTPClient http;
        USE_SERIAL.print("[HTTP] begin...\n");
        // configure traged server and url
        http.begin("http://server/test.php"); // HTTP

        http.addHeader("Content-Type", "application/x-www-form-urlencoded");
        http.POST("id=s1&api=123456789");
        http.writeToStream(&Serial);
        http.end();

        USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        int httpCode = http.GET();

        // httpCode will be negative on error
        if (httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if (httpCode == HTTP_CODE_OK) {
                String payload = http.getString();
                USE_SERIAL.println(payload);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n",
                                                http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(10000);
}

当我运行它时,我收到411错误代码。这里有什么不对?我怎么解决呢? 我在Postman中测试了这些参数并且它们没问题。

0 个答案:

没有答案