[英]HTTP POST using Arduino ESP8266 SparkFun Shield
我正在嘗試將 POST HTTP 發送到運行 node.js 的本地服務器。 GET 請求運行良好。 使用 Postman(本地)的 POST 運行良好,我沒有任何防火牆。 但我不能用 Arduino 運行它。
我使用的代碼是一個簡單的 SparkFun Client 示例,其中我只將 GET 更改為 POST:
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 是:
const String httpPost = "POST /meteo HTTP/1.1\n"
"Host: 192.168.0.131:5000\n"
"User-Agent: Arduino/1.0\n"
"Connection: close\n"
"Content-Type: application/x-www-form-urlencoded;\n"
"windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n";
我在串行監視器中得到的只是“與服務器連接!”...
我究竟做錯了什么?
標題和正文之間需要有一個空行:
const String httpPost = "POST /meteo HTTP/1.1\r\n"
"Host: 192.168.0.131:5000\r\n"
"User-Agent: Arduino/1.0\r\n"
"Connection: close\r\n"
"Content-Type: application/x-www-form-urlencoded;\r\n"
"\r\n"
"windspeedmph=0&winddir=0&humidity=0&temp=0&pressure=0\n";
同樣按照標准,您應該使用\\r\\n
來換行,而不僅僅是\\n
。
HTTP 標頭換行樣式
就我而言,指定 Content-Length 字段也很重要。 然后應用程序開始正常工作。 如果沒有 Content-Length 字段,接收方就看不到任何數據。 Content-Length 指定有效負載的長度,在您的情況下是字符串的長度:“windspeedmph=0&winddir=0&warmity=0&temp=0&pressure=0\\n”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.