HTTP POST using Arduino ESP8266 SparkFun Shield
我正在尝试将POST HTTP发送到运行node.js的本地服务器。 GET请求运行良好。 使用Postman(本地)的POST效果很好,我没有任何防火墙。 但是我不能用Arduino运行它。
我使用的代码是一个简单的SparkFun Client示例,其中我仅将GET更改为POST:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | void clientDemo() { // To use the ESP8266 as a TCP client, use the // ESP8266Client class. First, create an object: ESP8266Client client; // ESP8266Client connect([server], [port]) is used to // connect to a server (const char * or IPAddress) on // a specified port. // Returns: 1 on success, 2 on already connected, // negative on fail (-1=TIMEOUT, -3=FAIL). int retVal = client.connect(destServer, 5000); if (retVal == -1) { Serial.println(F("Time out")); return; } else if(retVal == -3) { Serial.println(F("Fail connection")); return; } else if(retVal == 1) { Serial.println("Connected with server!"); } // print and write can be used to send data to a connected // client connection. client.print(httpPost); // available() will return the number of characters // currently in the receive buffer. while (client.available()) Serial.write(client.read()); // read() gets the FIFO char // connected() is a boolean return value - 1 if the // connection is active, 0 if it's closed. if (client.connected()) client.stop(); // stop() closes a TCP connection. } |
而httpPost是:
1 2 3 4 5 6 7 8 9 10 11 12 | const String httpPost ="POST /meteo HTTP/1.1\ " "Host: 192.168.0.131:5000\ " "User-Agent: Arduino/1.0\ " "Connection: close\ " "Content-Type: application/x-www-form-urlencoded;\ " "windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\ "; |
我在串行监视器中看到的只是"与服务器连接!" ...
我究竟做错了什么?
就我而言,指定"内容长度"字段也很重要。 然后,该应用程序开始正常运行。 如果没有Content-Length字段,则在接收方看不到任何数据。 Content-Length指定有效负载的长度,在您的情况下为字符串的长度:" windspeedmph = 0&winddir = 0&湿度= 0&湿度= 0&temp = 0&pressure = 0 \ n"。
标头和正文之间必须有一个空行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | const String httpPost = "POST /meteo HTTP/1.1\ \ " "Host: 192.168.0.131:5000\ \ " "User-Agent: Arduino/1.0\ \ " "Connection: close\ \ " "Content-Type: application/x-www-form-urlencoded;\ \ " "\ \ " "windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\ "; |
同样,按照标准,您应该将
\
HTTP标头换行样式